@babylonjs/viewer 7.21.4 → 7.21.5-alpha

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (198) hide show
  1. package/dist/babylon-viewer.esm.js +114635 -0
  2. package/dist/babylon-viewer.esm.js.map +1 -0
  3. package/dist/babylon-viewer.esm.min.js +2 -0
  4. package/dist/babylon-viewer.esm.min.js.map +1 -0
  5. package/lib/index.d.ts +132 -0
  6. package/lib/index.js +369 -0
  7. package/lib/index.js.map +1 -0
  8. package/package.json +16 -29
  9. package/readme.md +35 -21
  10. package/configuration/configuration.d.ts +0 -107
  11. package/configuration/configuration.js +0 -16
  12. package/configuration/configuration.js.map +0 -1
  13. package/configuration/configurationCompatibility.d.ts +0 -8
  14. package/configuration/configurationCompatibility.js +0 -66
  15. package/configuration/configurationCompatibility.js.map +0 -1
  16. package/configuration/configurationContainer.d.ts +0 -10
  17. package/configuration/configurationContainer.js +0 -10
  18. package/configuration/configurationContainer.js.map +0 -1
  19. package/configuration/globals.d.ts +0 -6
  20. package/configuration/globals.js +0 -18
  21. package/configuration/globals.js.map +0 -1
  22. package/configuration/index.d.ts +0 -2
  23. package/configuration/index.js +0 -4
  24. package/configuration/index.js.map +0 -1
  25. package/configuration/interfaces/cameraConfiguration.d.ts +0 -31
  26. package/configuration/interfaces/cameraConfiguration.js +0 -2
  27. package/configuration/interfaces/cameraConfiguration.js.map +0 -1
  28. package/configuration/interfaces/colorGradingConfiguration.d.ts +0 -81
  29. package/configuration/interfaces/colorGradingConfiguration.js +0 -2
  30. package/configuration/interfaces/colorGradingConfiguration.js.map +0 -1
  31. package/configuration/interfaces/defaultRenderingPipelineConfiguration.d.ts +0 -20
  32. package/configuration/interfaces/defaultRenderingPipelineConfiguration.js +0 -2
  33. package/configuration/interfaces/defaultRenderingPipelineConfiguration.js.map +0 -1
  34. package/configuration/interfaces/environmentMapConfiguration.d.ts +0 -22
  35. package/configuration/interfaces/environmentMapConfiguration.js +0 -2
  36. package/configuration/interfaces/environmentMapConfiguration.js.map +0 -1
  37. package/configuration/interfaces/groundConfiguration.d.ts +0 -24
  38. package/configuration/interfaces/groundConfiguration.js +0 -2
  39. package/configuration/interfaces/groundConfiguration.js.map +0 -1
  40. package/configuration/interfaces/imageProcessingConfiguration.d.ts +0 -45
  41. package/configuration/interfaces/imageProcessingConfiguration.js +0 -2
  42. package/configuration/interfaces/imageProcessingConfiguration.js.map +0 -1
  43. package/configuration/interfaces/index.d.ts +0 -15
  44. package/configuration/interfaces/index.js +0 -16
  45. package/configuration/interfaces/index.js.map +0 -1
  46. package/configuration/interfaces/lightConfiguration.d.ts +0 -60
  47. package/configuration/interfaces/lightConfiguration.js +0 -2
  48. package/configuration/interfaces/lightConfiguration.js.map +0 -1
  49. package/configuration/interfaces/modelAnimationConfiguration.d.ts +0 -26
  50. package/configuration/interfaces/modelAnimationConfiguration.js +0 -2
  51. package/configuration/interfaces/modelAnimationConfiguration.js.map +0 -1
  52. package/configuration/interfaces/modelConfiguration.d.ts +0 -65
  53. package/configuration/interfaces/modelConfiguration.js +0 -2
  54. package/configuration/interfaces/modelConfiguration.js.map +0 -1
  55. package/configuration/interfaces/observersConfiguration.d.ts +0 -5
  56. package/configuration/interfaces/observersConfiguration.js +0 -2
  57. package/configuration/interfaces/observersConfiguration.js.map +0 -1
  58. package/configuration/interfaces/sceneConfiguration.d.ts +0 -48
  59. package/configuration/interfaces/sceneConfiguration.js +0 -2
  60. package/configuration/interfaces/sceneConfiguration.js.map +0 -1
  61. package/configuration/interfaces/sceneOptimizerConfiguration.d.ts +0 -23
  62. package/configuration/interfaces/sceneOptimizerConfiguration.js +0 -2
  63. package/configuration/interfaces/sceneOptimizerConfiguration.js.map +0 -1
  64. package/configuration/interfaces/skyboxConfiguration.d.ts +0 -21
  65. package/configuration/interfaces/skyboxConfiguration.js +0 -2
  66. package/configuration/interfaces/skyboxConfiguration.js.map +0 -1
  67. package/configuration/interfaces/templateConfiguration.d.ts +0 -67
  68. package/configuration/interfaces/templateConfiguration.js +0 -2
  69. package/configuration/interfaces/templateConfiguration.js.map +0 -1
  70. package/configuration/interfaces/vrConfiguration.d.ts +0 -16
  71. package/configuration/interfaces/vrConfiguration.js +0 -2
  72. package/configuration/interfaces/vrConfiguration.js.map +0 -1
  73. package/configuration/loader.d.ts +0 -4
  74. package/configuration/loader.js +0 -17
  75. package/configuration/loader.js.map +0 -1
  76. package/configuration/mappers.d.ts +0 -43
  77. package/configuration/mappers.js +0 -192
  78. package/configuration/mappers.js.map +0 -1
  79. package/configuration/renderOnlyLoader.d.ts +0 -33
  80. package/configuration/renderOnlyLoader.js +0 -162
  81. package/configuration/renderOnlyLoader.js.map +0 -1
  82. package/configuration/types/default.d.ts +0 -6
  83. package/configuration/types/default.js +0 -121
  84. package/configuration/types/default.js.map +0 -1
  85. package/configuration/types/environmentMap.d.ts +0 -5
  86. package/configuration/types/environmentMap.js +0 -14
  87. package/configuration/types/environmentMap.js.map +0 -1
  88. package/configuration/types/extended.d.ts +0 -6
  89. package/configuration/types/extended.js +0 -317
  90. package/configuration/types/extended.js.map +0 -1
  91. package/configuration/types/index.d.ts +0 -14
  92. package/configuration/types/index.js +0 -51
  93. package/configuration/types/index.js.map +0 -1
  94. package/configuration/types/minimal.d.ts +0 -6
  95. package/configuration/types/minimal.js +0 -43
  96. package/configuration/types/minimal.js.map +0 -1
  97. package/configuration/types/renderOnlyDefault.d.ts +0 -30
  98. package/configuration/types/renderOnlyDefault.js +0 -31
  99. package/configuration/types/renderOnlyDefault.js.map +0 -1
  100. package/configuration/types/shadowLight.d.ts +0 -9
  101. package/configuration/types/shadowLight.js +0 -64
  102. package/configuration/types/shadowLight.js.map +0 -1
  103. package/helper/index.d.ts +0 -29
  104. package/helper/index.js +0 -66
  105. package/helper/index.js.map +0 -1
  106. package/index.d.ts +0 -30
  107. package/index.js +0 -46
  108. package/index.js.map +0 -1
  109. package/initializer.d.ts +0 -11
  110. package/initializer.js +0 -35
  111. package/initializer.js.map +0 -1
  112. package/interfaces.d.ts +0 -5
  113. package/interfaces.js +0 -7
  114. package/interfaces.js.map +0 -1
  115. package/labs/environmentSerializer.d.ts +0 -126
  116. package/labs/environmentSerializer.js +0 -191
  117. package/labs/environmentSerializer.js.map +0 -1
  118. package/labs/texture.d.ts +0 -183
  119. package/labs/texture.js +0 -351
  120. package/labs/texture.js.map +0 -1
  121. package/labs/viewerLabs.d.ts +0 -51
  122. package/labs/viewerLabs.js +0 -134
  123. package/labs/viewerLabs.js.map +0 -1
  124. package/loader/modelLoader.d.ts +0 -56
  125. package/loader/modelLoader.js +0 -199
  126. package/loader/modelLoader.js.map +0 -1
  127. package/loader/plugins/applyMaterialConfig.d.ts +0 -12
  128. package/loader/plugins/applyMaterialConfig.js +0 -16
  129. package/loader/plugins/applyMaterialConfig.js.map +0 -1
  130. package/loader/plugins/extendedMaterialLoaderPlugin.d.ts +0 -9
  131. package/loader/plugins/extendedMaterialLoaderPlugin.js +0 -16
  132. package/loader/plugins/extendedMaterialLoaderPlugin.js.map +0 -1
  133. package/loader/plugins/index.d.ts +0 -19
  134. package/loader/plugins/index.js +0 -44
  135. package/loader/plugins/index.js.map +0 -1
  136. package/loader/plugins/loaderPlugin.d.ts +0 -24
  137. package/loader/plugins/loaderPlugin.js +0 -2
  138. package/loader/plugins/loaderPlugin.js.map +0 -1
  139. package/loader/plugins/msftLodLoaderPlugin.d.ts +0 -12
  140. package/loader/plugins/msftLodLoaderPlugin.js +0 -21
  141. package/loader/plugins/msftLodLoaderPlugin.js.map +0 -1
  142. package/loader/plugins/telemetryLoaderPlugin.d.ts +0 -12
  143. package/loader/plugins/telemetryLoaderPlugin.js +0 -36
  144. package/loader/plugins/telemetryLoaderPlugin.js.map +0 -1
  145. package/managers/observablesManager.d.ts +0 -66
  146. package/managers/observablesManager.js +0 -35
  147. package/managers/observablesManager.js.map +0 -1
  148. package/managers/sceneManager.d.ts +0 -245
  149. package/managers/sceneManager.js +0 -1375
  150. package/managers/sceneManager.js.map +0 -1
  151. package/managers/telemetryManager.d.ts +0 -78
  152. package/managers/telemetryManager.js +0 -117
  153. package/managers/telemetryManager.js.map +0 -1
  154. package/model/modelAnimation.d.ts +0 -215
  155. package/model/modelAnimation.js +0 -237
  156. package/model/modelAnimation.js.map +0 -1
  157. package/model/viewerModel.d.ts +0 -233
  158. package/model/viewerModel.js +0 -673
  159. package/model/viewerModel.js.map +0 -1
  160. package/optimizer/custom/extended.d.ts +0 -13
  161. package/optimizer/custom/extended.js +0 -101
  162. package/optimizer/custom/extended.js.map +0 -1
  163. package/optimizer/custom/index.d.ts +0 -9
  164. package/optimizer/custom/index.js +0 -26
  165. package/optimizer/custom/index.js.map +0 -1
  166. package/renderOnlyIndex.d.ts +0 -11
  167. package/renderOnlyIndex.js +0 -18
  168. package/renderOnlyIndex.js.map +0 -1
  169. package/templating/eventManager.d.ts +0 -35
  170. package/templating/eventManager.js +0 -66
  171. package/templating/eventManager.js.map +0 -1
  172. package/templating/plugins/hdButtonPlugin.d.ts +0 -9
  173. package/templating/plugins/hdButtonPlugin.js +0 -21
  174. package/templating/plugins/hdButtonPlugin.js.map +0 -1
  175. package/templating/plugins/printButton.d.ts +0 -9
  176. package/templating/plugins/printButton.js +0 -40
  177. package/templating/plugins/printButton.js.map +0 -1
  178. package/templating/templateManager.d.ts +0 -197
  179. package/templating/templateManager.js +0 -561
  180. package/templating/templateManager.js.map +0 -1
  181. package/templating/viewerTemplatePlugin.d.ts +0 -21
  182. package/templating/viewerTemplatePlugin.js +0 -69
  183. package/templating/viewerTemplatePlugin.js.map +0 -1
  184. package/viewer/defaultViewer.d.ts +0 -130
  185. package/viewer/defaultViewer.js +0 -675
  186. package/viewer/defaultViewer.js.map +0 -1
  187. package/viewer/renderOnlyViewer.d.ts +0 -9
  188. package/viewer/renderOnlyViewer.js +0 -46
  189. package/viewer/renderOnlyViewer.js.map +0 -1
  190. package/viewer/viewer.d.ts +0 -258
  191. package/viewer/viewer.js +0 -783
  192. package/viewer/viewer.js.map +0 -1
  193. package/viewer/viewerManager.d.ts +0 -58
  194. package/viewer/viewerManager.js +0 -91
  195. package/viewer/viewerManager.js.map +0 -1
  196. package/viewer/viewerWithTemplate.d.ts +0 -9
  197. package/viewer/viewerWithTemplate.js +0 -20
  198. package/viewer/viewerWithTemplate.js.map +0 -1
@@ -0,0 +1,2 @@
1
+ function e(e,t,i,n){var r,s=arguments.length,a=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(a=(s<3?r(a):s>3?r(t,i,a):r(t,i))||a);return s>3&&a&&Object.defineProperty(t,i,a),a}"function"==typeof SuppressedError&&SuppressedError;const t={},i={};function n(e){const n=e.getClassName();if(t[n])return t[n];t[n]={};const r=t[n];let s=e,a=n;for(;a;){const e=i[a];for(const t in e)r[t]=e[t];let t,n=!1;do{if(t=Object.getPrototypeOf(s),!t.getClassName){n=!0;break}if(t.getClassName()!==a)break;s=t}while(t);if(n)break;a=t.getClassName(),s=t}return r}function r(e,t){return(n,r)=>{const s=function(e){const t=e.getClassName();return i[t]||(i[t]={}),i[t]}(n);s[r]||(s[r]={type:e,sourceName:t})}}function s(e,t=null){return function(e,t=null){return(i,n)=>{const r=t||"_"+n;Object.defineProperty(i,n,{get:function(){return this[r]},set:function(t){"function"==typeof this.equals&&this.equals(t)||this[r]!==t&&(this[r]=t,i[e].apply(this))},enumerable:!0,configurable:!0})}}(e,t)}function a(e){return r(0,e)}function o(e){return r(1,e)}function l(e){return r(2,e)}function c(e){return r(4,e)}function h(e){return r(5,e)}function d(e){return r(6,e)}function u(e){return r(8,e)}function f(e){return r(12,e)}function _(e,t,i,n){const r=i.value;i.value=(...i)=>{let s=r;if("undefined"!=typeof _native&&_native[t]){const e=_native[t];s=n?(...t)=>n(...t)?e(...t):r(...t):e}return e[t]=s,s(...i)}}_.filter=function(e){return(t,i,n)=>_(t,i,n,e)};class m{constructor(e,t=!1,i,n){this.initialize(e,t,i,n)}initialize(e,t=!1,i,n){return this.mask=e,this.skipNextObservers=t,this.target=i,this.currentTarget=n,this}}class p{constructor(e,t,i=null){this.callback=e,this.mask=t,this.scope=i,this._willBeUnregistered=!1,this.unregisterOnNextCall=!1,this._remove=null}remove(){this._remove&&this._remove()}}class g{static FromPromise(e,t){const i=new g;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 m(0),e&&(this._onObserverAdded=e)}add(e,t=-1,i=!1,n=null,r=!1){if(!e)return null;const s=new p(e,t,n);return s.unregisterOnNextCall=r,i?this._observers.unshift(s):this._observers.push(s),this._onObserverAdded&&this._onObserverAdded(s),this._hasNotified&&this.notifyIfTriggered&&void 0!==this._lastNotifiedValue&&this.notifyObserver(s,this._lastNotifiedValue),s._remove=()=>{this.remove(s)},s}addOnce(e){return this.add(e,void 0,void 0,void 0,!0)}remove(e){if(!e)return!1;e._remove=null;return-1!==this._observers.indexOf(e)&&(this._deferUnregister(e),!0)}removeCallback(e,t){for(let i=0;i<this._observers.length;i++){const n=this._observers[i];if(!n._willBeUnregistered&&(n.callback===e&&(!t||t===n.scope)))return this._deferUnregister(n),!0}return!1}_deferUnregister(e){e._willBeUnregistered||(this._numObserversMarkedAsDeleted++,e.unregisterOnNextCall=!1,e._willBeUnregistered=!0,setTimeout((()=>{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,n,r){if(this.notifyIfTriggered&&(this._hasNotified=!0,this._lastNotifiedValue=e),!this._observers.length)return!0;const s=this._eventState;s.mask=t,s.target=i,s.currentTarget=n,s.skipNextObservers=!1,s.lastReturnValue=e,s.userInfo=r;for(const i of this._observers)if(!i._willBeUnregistered&&(i.mask&t&&(i.unregisterOnNextCall&&this._deferUnregister(i),i.scope?s.lastReturnValue=i.callback.apply(i.scope,[e,s]):s.lastReturnValue=i.callback(e,s)),s.skipNextObservers))return!1;return!0}notifyObserver(e,t,i=-1){if(this.notifyIfTriggered&&(this._hasNotified=!0,this._lastNotifiedValue=t),e._willBeUnregistered)return;const n=this._eventState;n.mask=i,n.skipNextObservers=!1,e.unregisterOnNextCall&&this._deferUnregister(e),e.callback(t,n)}hasObservers(){return this._observers.length-this._numObserversMarkedAsDeleted>0}clear(){for(;this._observers.length;){const e=this._observers.pop();e&&(e._remove=null)}this._onObserverAdded=null,this._numObserversMarkedAsDeleted=0,this.cleanLastNotifiedState()}cleanLastNotifiedState(){this._hasNotified=!1,this._lastNotifiedValue=void 0}clone(){const e=new g;return e._observers=this._observers.slice(0),e}hasSpecificMask(e=-1){for(const t of this._observers)if(t.mask&e||t.mask===e)return!0;return!1}}const E=1/2.2,T=2.2,A=.001;function v(e,t){const i=[];for(let n=0;n<e;++n)i.push(t());return i}function R(e,t){return v(e,t)}const S=["push","splice","pop","shift","unshift"];function I(e,t){const i=S.map((i=>function(e,t,i){const n=e[t];if("function"!=typeof n)return null;const r=function(){const n=e.length,s=r.previous.apply(e,arguments);return i(t,n),s};return n.next=r,r.previous=n,e[t]=r,()=>{const i=r.previous;if(!i)return;const n=r.next;n?(i.next=n,n.previous=i):(i.next=void 0,e[t]=i),r.next=void 0,r.previous=void 0}}(e,i,t)));return()=>{i.forEach((e=>{e?.()}))}}const C={};function M(e,t){C[e]=t}function x(e){return C[e]}class b{static SetMatrixPrecision(e){if(b.MatrixTrackPrecisionChange=!1,e&&!b.MatrixUse64Bits&&b.MatrixTrackedMatrices)for(let e=0;e<b.MatrixTrackedMatrices.length;++e){const t=b.MatrixTrackedMatrices[e],i=t._m;t._m=new Array(16);for(let e=0;e<16;++e)t._m[e]=i[e]}b.MatrixUse64Bits=e,b.MatrixCurrentType=b.MatrixUse64Bits?Array:Float32Array,b.MatrixTrackedMatrices=null}}b.MatrixUse64Bits=!1,b.MatrixTrackPrecisionChange=!0,b.MatrixCurrentType=Float32Array,b.MatrixTrackedMatrices=[];class y{static get LastCreatedEngine(){return 0===this.Instances.length?null:this.Instances[this.Instances.length-1]}static get LastCreatedScene(){return this._LastCreatedScene}}function O(e,t,i=1401298e-51){return Math.abs(e-t)<=i}function D(e,t){return e===t?e:Math.random()*(t-e)+e}function N(e,t,i){return e+(t-e)*i}function P(e,t=0,i=1){return Math.min(i,Math.max(t,e))}function L(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()}y.Instances=[],y.OnEnginesDisposedObservable=new g,y._LastCreatedScene=null,y.UseFallbackTexture=!0,y.FallbackTexture="";const w=e=>parseInt(e.toString().replace(/\W/g,""));class U{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=w(this.x);return e=397*e^w(this.y),e}toArray(e,t=0){return e[t]=this.x,e[t+1]=this.y,this}fromArray(e,t=0){return U.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 U(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 U(this.x+e.x,this.y+e.y)}subtract(e){return new U(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 U(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 U(this.x*e,this.y*t)}divide(e){return new U(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 U(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 U(-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 U(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=A){return e&&O(this.x,e.x,t)&&O(this.y,e.y,t)}equalsToFloats(e,t){return this.x===e&&this.y===t}floor(){return new U(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 U(this.x-Math.floor(this.x),this.y-Math.floor(this.y))}fractToRef(e){return e.x=this.x-Math.floor(this.x),e.y=this.y-Math.floor(this.y),e}rotateToRef(e,t){const i=Math.cos(e),n=Math.sin(e),r=i*this.x-n*this.y,s=n*this.x+i*this.y;return t.x=r,t.y=s,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 U;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 U(this.x,this.y)}dot(e){return this.x*e.x+this.y*e.y}static Zero(){return new U(0,0)}static One(){return new U(1,1)}static Random(e=0,t=1){return new U(D(e,t),D(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats(D(e,t),D(e,t))}static get ZeroReadOnly(){return U._ZeroReadOnly}static FromArray(e,t=0){return new U(e[t],e[t+1])}static FromArrayToRef(e,t,i){return i.x=e[t],i.y=e[t+1],i}static FromFloatsToRef(e,t,i){return i.copyFromFloats(e,t),i}static CatmullRom(e,t,i,n,r){const s=r*r,a=r*s,o=.5*(2*t.x+(-e.x+i.x)*r+(2*e.x-5*t.x+4*i.x-n.x)*s+(-e.x+3*t.x-3*i.x+n.x)*a),l=.5*(2*t.y+(-e.y+i.y)*r+(2*e.y-5*t.y+4*i.y-n.y)*s+(-e.y+3*t.y-3*i.y+n.y)*a);return new U(o,l)}static ClampToRef(e,t,i,n){return n.x=P(e.x,t.x,i.x),n.y=P(e.y,t.y,i.y),n}static Clamp(e,t,i){const n=P(e.x,t.x,i.x),r=P(e.y,t.y,i.y);return new U(n,r)}static Hermite(e,t,i,n,r){const s=r*r,a=r*s,o=2*a-3*s+1,l=-2*a+3*s,c=a-2*s+r,h=a-s,d=e.x*o+i.x*l+t.x*c+n.x*h,u=e.y*o+i.y*l+t.y*c+n.y*h;return new U(d,u)}static Hermite1stDerivative(e,t,i,n,r){return this.Hermite1stDerivativeToRef(e,t,i,n,r,new U)}static Hermite1stDerivativeToRef(e,t,i,n,r,s){const a=r*r;return s.x=6*(a-r)*e.x+(3*a-4*r+1)*t.x+6*(-a+r)*i.x+(3*a-2*r)*n.x,s.y=6*(a-r)*e.y+(3*a-4*r+1)*t.y+6*(-a+r)*i.y+(3*a-2*r)*n.y,s}static Lerp(e,t,i){return U.LerpToRef(e,t,i,new U)}static LerpToRef(e,t,i,n){return n.x=e.x+(t.x-e.x)*i,n.y=e.y+(t.y-e.y)*i,n}static Dot(e,t){return e.x*t.x+e.y*t.y}static Normalize(e){return U.NormalizeToRef(e,new U)}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Minimize(e,t){const i=e.x<t.x?e.x:t.x,n=e.y<t.y?e.y:t.y;return new U(i,n)}static Maximize(e,t){const i=e.x>t.x?e.x:t.x,n=e.y>t.y?e.y:t.y;return new U(i,n)}static Transform(e,t){return U.TransformToRef(e,t,new U)}static TransformToRef(e,t,i){const n=t.m,r=e.x*n[0]+e.y*n[4]+n[12],s=e.x*n[1]+e.y*n[5]+n[13];return i.x=r,i.y=s,i}static PointInTriangle(e,t,i,n){const r=.5*(-i.y*n.x+t.y*(-i.x+n.x)+t.x*(i.y-n.y)+i.x*n.y),s=r<0?-1:1,a=(t.y*n.x-t.x*n.y+(n.y-t.y)*e.x+(t.x-n.x)*e.y)*s,o=(t.x*i.y-t.y*i.x+(t.y-i.y)*e.x+(i.x-t.x)*e.y)*s;return a>0&&o>0&&a+o<2*r*s}static Distance(e,t){return Math.sqrt(U.DistanceSquared(e,t))}static DistanceSquared(e,t){const i=e.x-t.x,n=e.y-t.y;return i*i+n*n}static Center(e,t){return U.CenterToRef(e,t,new U)}static CenterToRef(e,t,i){return i.copyFromFloats((e.x+t.x)/2,(e.y+t.y)/2)}static DistanceOfPointFromSegment(e,t,i){const n=U.DistanceSquared(t,i);if(0===n)return U.Distance(e,t);const r=i.subtract(t),s=Math.max(0,Math.min(1,U.Dot(e.subtract(t),r)/n)),a=t.add(r.multiplyByFloats(s,s));return U.Distance(e,a)}}U._ZeroReadOnly=U.Zero(),Object.defineProperties(U.prototype,{dimension:{value:[2]},rank:{value:1}});class B{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=w(this._x);return e=397*e^w(this._y),e=397*e^w(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 B.FromArrayToRef(e,t,this),this}toQuaternion(){return V.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 B(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 B(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 B(this._x-e,this._y-t,this._z-i)}subtractFromFloatsToRef(e,t,i,n){return n._x=this._x-e,n._y=this._y-t,n._z=this._z-i,n._isDirty=!0,n}negate(){return new B(-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 B(this._x*e,this._y*e,this._z*e)}scaleToRef(e,t){return t._x=this._x*e,t._y=this._y*e,t._z=this._z*e,t._isDirty=!0,t}getNormalToRef(e){const t=this.length();let i=Math.acos(this.y/t);const n=Math.atan2(this.z,this.x);i>Math.PI/2?i-=Math.PI/2:i+=Math.PI/2;const r=t*Math.sin(i)*Math.cos(n),s=t*Math.cos(i),a=t*Math.sin(i)*Math.sin(n);return e.set(r,s,a),e}applyRotationQuaternionToRef(e,t){const i=this._x,n=this._y,r=this._z,s=e._x,a=e._y,o=e._z,l=e._w,c=2*(a*r-o*n),h=2*(o*i-s*r),d=2*(s*n-a*i);return t._x=i+l*c+a*d-o*h,t._y=n+l*h+o*c-s*d,t._z=r+l*d+s*h-a*c,t._isDirty=!0,t}applyRotationQuaternionInPlace(e){return this.applyRotationQuaternionToRef(e,this)}applyRotationQuaternion(e){return this.applyRotationQuaternionToRef(e,new B)}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 B)}projectOnPlaneToRef(e,t,i){const n=e.normal,r=e.d,s=X.Vector3[0];this.subtractToRef(t,s),s.normalize();const a=B.Dot(s,n);if(Math.abs(a)<1e-10)i.setAll(1/0);else{const e=-(B.Dot(t,n)+r)/a,o=s.scaleInPlace(e);t.addToRef(o,i)}return i}equals(e){return e&&this._x===e._x&&this._y===e._y&&this._z===e._z}equalsWithEpsilon(e,t=A){return e&&O(this._x,e._x,t)&&O(this._y,e._y,t)&&O(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 B(this._x*e,this._y*t,this._z*i)}divide(e){return new B(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 e<this._x&&(this.x=e),t<this._y&&(this.y=t),i<this._z&&(this.z=i),this}maximizeInPlaceFromFloats(e,t,i){return e>this._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(!O(t,i,e))return!0;const n=Math.abs(this._z);return!O(t,n,e)||!O(i,n,e)}get isNonUniform(){const e=Math.abs(this._x);if(e!==Math.abs(this._y))return!0;return 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 B(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 B(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=X.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(X.Matrix[0]),B.TransformCoordinatesToRef(this,X.Matrix[0],t),t}rotateByQuaternionAroundPointToRef(e,t,i){return this.subtractToRef(t,X.Vector3[0]),X.Vector3[0].rotateByQuaternionToRef(e,X.Vector3[0]),t.addToRef(X.Vector3[0],i),i}cross(e){return B.CrossToRef(this,e,new B)}normalizeFromLength(e){return 0===e||1===e?this:this.scaleInPlace(1/e)}normalizeToNew(){return this.normalizeToRef(new B)}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 B(this._x,this._y,this._z)}copyFrom(e){return this.copyFromFloats(e._x,e._y,e._z)}copyFromFloats(e,t,i){return this._x=e,this._y=t,this._z=i,this._isDirty=!0,this}set(e,t,i){return this.copyFromFloats(e,t,i)}setAll(e){return this._x=this._y=this._z=e,this._isDirty=!0,this}static GetClipFactor(e,t,i,n){const r=B.Dot(e,i);return(r-n)/(r-B.Dot(t,i))}static GetAngleBetweenVectors(e,t,i){const n=e.normalizeToRef(X.Vector3[1]),r=t.normalizeToRef(X.Vector3[2]);let s=B.Dot(n,r);s=P(s,-1,1);const a=Math.acos(s),o=X.Vector3[3];return B.CrossToRef(n,r,o),B.Dot(o,i)>0?isNaN(a)?0:a:isNaN(a)?-Math.PI:-Math.acos(s)}static GetAngleBetweenVectorsOnPlane(e,t,i){X.Vector3[0].copyFrom(e);const n=X.Vector3[0];X.Vector3[1].copyFrom(t);const r=X.Vector3[1];X.Vector3[2].copyFrom(i);const s=X.Vector3[2],a=X.Vector3[3],o=X.Vector3[4];n.normalize(),r.normalize(),s.normalize(),B.CrossToRef(s,n,a),B.CrossToRef(a,s,o);return L(Math.atan2(B.Dot(r,a),B.Dot(r,o)))}static PitchYawRollToMoveBetweenPointsToRef(e,t,i){const n=H.Vector3[0];return t.subtractToRef(e,n),i._y=Math.atan2(n.x,n.z)||0,i._x=Math.atan2(Math.sqrt(n.x**2+n.z**2),n.y)||0,i._z=0,i._isDirty=!0,i}static PitchYawRollToMoveBetweenPoints(e,t){const i=B.Zero();return B.PitchYawRollToMoveBetweenPointsToRef(e,t,i)}static SlerpToRef(e,t,i,n){i=P(i,0,1);const r=X.Vector3[0],s=X.Vector3[1];r.copyFrom(e);const a=r.length();r.normalizeFromLength(a),s.copyFrom(t);const o=s.length();s.normalizeFromLength(o);const l=B.Dot(r,s);let c,h;if(l<1-A){const e=Math.acos(l),t=1/Math.sin(e);c=Math.sin((1-i)*e)*t,h=Math.sin(i*e)*t}else c=1-i,h=i;return r.scaleInPlace(c),s.scaleInPlace(h),n.copyFrom(r).addInPlace(s),n.scaleInPlace(N(a,o,i)),n}static SmoothToRef(e,t,i,n,r){return B.SlerpToRef(e,t,0===n?1:i/n,r),r}static FromArray(e,t=0){return new B(e[t],e[t+1],e[t+2])}static FromFloatArray(e,t){return B.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 B.FromArrayToRef(e,t,i)}static FromFloatsToRef(e,t,i,n){return n.copyFromFloats(e,t,i),n}static Zero(){return new B(0,0,0)}static One(){return new B(1,1,1)}static Up(){return new B(0,1,0)}static get UpReadOnly(){return B._UpReadOnly}static get DownReadOnly(){return B._DownReadOnly}static get RightReadOnly(){return B._RightReadOnly}static get LeftReadOnly(){return B._LeftReadOnly}static get LeftHandedForwardReadOnly(){return B._LeftHandedForwardReadOnly}static get RightHandedForwardReadOnly(){return B._RightHandedForwardReadOnly}static get LeftHandedBackwardReadOnly(){return B._LeftHandedBackwardReadOnly}static get RightHandedBackwardReadOnly(){return B._RightHandedBackwardReadOnly}static get ZeroReadOnly(){return B._ZeroReadOnly}static get OneReadOnly(){return B._OneReadOnly}static Down(){return new B(0,-1,0)}static Forward(e=!1){return new B(0,0,e?-1:1)}static Backward(e=!1){return new B(0,0,e?1:-1)}static Right(){return new B(1,0,0)}static Left(){return new B(-1,0,0)}static Random(e=0,t=1){return new B(D(e,t),D(e,t),D(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats(D(e,t),D(e,t),D(e,t))}static TransformCoordinates(e,t){const i=B.Zero();return B.TransformCoordinatesToRef(e,t,i),i}static TransformCoordinatesToRef(e,t,i){return B.TransformCoordinatesFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformCoordinatesFromFloatsToRef(e,t,i,n,r){const s=n.m,a=e*s[0]+t*s[4]+i*s[8]+s[12],o=e*s[1]+t*s[5]+i*s[9]+s[13],l=e*s[2]+t*s[6]+i*s[10]+s[14],c=1/(e*s[3]+t*s[7]+i*s[11]+s[15]);return r._x=a*c,r._y=o*c,r._z=l*c,r._isDirty=!0,r}static TransformNormal(e,t){const i=B.Zero();return B.TransformNormalToRef(e,t,i),i}static TransformNormalToRef(e,t,i){return this.TransformNormalFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformNormalFromFloatsToRef(e,t,i,n,r){const s=n.m;return r._x=e*s[0]+t*s[4]+i*s[8],r._y=e*s[1]+t*s[5]+i*s[9],r._z=e*s[2]+t*s[6]+i*s[10],r._isDirty=!0,r}static CatmullRom(e,t,i,n,r){const s=r*r,a=r*s,o=.5*(2*t._x+(-e._x+i._x)*r+(2*e._x-5*t._x+4*i._x-n._x)*s+(-e._x+3*t._x-3*i._x+n._x)*a),l=.5*(2*t._y+(-e._y+i._y)*r+(2*e._y-5*t._y+4*i._y-n._y)*s+(-e._y+3*t._y-3*i._y+n._y)*a),c=.5*(2*t._z+(-e._z+i._z)*r+(2*e._z-5*t._z+4*i._z-n._z)*s+(-e._z+3*t._z-3*i._z+n._z)*a);return new B(o,l,c)}static Clamp(e,t,i){const n=new B;return B.ClampToRef(e,t,i,n),n}static ClampToRef(e,t,i,n){let r=e._x;r=r>i._x?i._x:r,r=r<t._x?t._x:r;let s=e._y;s=s>i._y?i._y:s,s=s<t._y?t._y:s;let a=e._z;return a=a>i._z?i._z:a,a=a<t._z?t._z:a,n.copyFromFloats(r,s,a),n}static CheckExtends(e,t,i){t.minimizeInPlace(e),i.maximizeInPlace(e)}static Hermite(e,t,i,n,r){const s=r*r,a=r*s,o=2*a-3*s+1,l=-2*a+3*s,c=a-2*s+r,h=a-s,d=e._x*o+i._x*l+t._x*c+n._x*h,u=e._y*o+i._y*l+t._y*c+n._y*h,f=e._z*o+i._z*l+t._z*c+n._z*h;return new B(d,u,f)}static Hermite1stDerivative(e,t,i,n,r){const s=new B;return this.Hermite1stDerivativeToRef(e,t,i,n,r,s),s}static Hermite1stDerivativeToRef(e,t,i,n,r,s){const a=r*r;return s._x=6*(a-r)*e._x+(3*a-4*r+1)*t._x+6*(-a+r)*i._x+(3*a-2*r)*n._x,s._y=6*(a-r)*e._y+(3*a-4*r+1)*t._y+6*(-a+r)*i._y+(3*a-2*r)*n._y,s._z=6*(a-r)*e._z+(3*a-4*r+1)*t._z+6*(-a+r)*i._z+(3*a-2*r)*n._z,s._isDirty=!0,s}static Lerp(e,t,i){const n=new B(0,0,0);return B.LerpToRef(e,t,i,n),n}static LerpToRef(e,t,i,n){return n._x=e._x+(t._x-e._x)*i,n._y=e._y+(t._y-e._y)*i,n._z=e._z+(t._z-e._z)*i,n._isDirty=!0,n}static Dot(e,t){return e._x*t._x+e._y*t._y+e._z*t._z}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z}static Cross(e,t){const i=new B;return B.CrossToRef(e,t,i),i}static CrossToRef(e,t,i){const n=e._y*t._z-e._z*t._y,r=e._z*t._x-e._x*t._z,s=e._x*t._y-e._y*t._x;return i.copyFromFloats(n,r,s),i}static Normalize(e){const t=B.Zero();return B.NormalizeToRef(e,t),t}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Project(e,t,i,n){const r=new B;return B.ProjectToRef(e,t,i,n,r),r}static ProjectToRef(e,t,i,n,r){const s=n.width,a=n.height,o=n.x,l=n.y,c=X.Matrix[1],h=y.LastCreatedEngine?.isNDCHalfZRange,d=h?1:.5,u=h?0:.5;k.FromValuesToRef(s/2,0,0,0,0,-a/2,0,0,0,0,d,0,o+s/2,a/2+l,u,1,c);const f=X.Matrix[0];return t.multiplyToRef(i,f),f.multiplyToRef(c,f),B.TransformCoordinatesToRef(e,f,r),r}static Reflect(e,t){return this.ReflectToRef(e,t,new B)}static ReflectToRef(e,t,i){const n=H.Vector3[0];return n.copyFrom(t).scaleInPlace(2*B.Dot(e,t)),i.copyFrom(e).subtractInPlace(n)}static _UnprojectFromInvertedMatrixToRef(e,t,i){B.TransformCoordinatesToRef(e,t,i);const n=t.m,r=e._x*n[3]+e._y*n[7]+e._z*n[11]+n[15];return O(r,1)&&i.scaleInPlace(1/r),i}static UnprojectFromTransform(e,t,i,n,r){return this.Unproject(e,t,i,n,r,k.IdentityReadOnly)}static Unproject(e,t,i,n,r,s){const a=new B;return B.UnprojectToRef(e,t,i,n,r,s,a),a}static UnprojectToRef(e,t,i,n,r,s,a){return B.UnprojectFloatsToRef(e._x,e._y,e._z,t,i,n,r,s,a),a}static UnprojectFloatsToRef(e,t,i,n,r,s,a,o,l){const c=X.Matrix[0];s.multiplyToRef(a,c),c.multiplyToRef(o,c),c.invert();const h=X.Vector3[0];return h.x=e/n*2-1,h.y=-(t/r*2-1),y.LastCreatedEngine?.isNDCHalfZRange?h.z=i:h.z=2*i-1,B._UnprojectFromInvertedMatrixToRef(h,c,l),l}static Minimize(e,t){const i=new B;return i.copyFrom(e),i.minimizeInPlace(t),i}static Maximize(e,t){const i=new B;return i.copyFrom(e),i.maximizeInPlace(t),i}static Distance(e,t){return Math.sqrt(B.DistanceSquared(e,t))}static DistanceSquared(e,t){const i=e._x-t._x,n=e._y-t._y,r=e._z-t._z;return i*i+n*n+r*r}static ProjectOnTriangleToRef(e,t,i,n,r){const s=X.Vector3[0],a=X.Vector3[1],o=X.Vector3[2],l=X.Vector3[3],c=X.Vector3[4];i.subtractToRef(t,s),n.subtractToRef(t,a),n.subtractToRef(i,o);const h=s.length(),d=a.length(),u=o.length();if(h<A||d<A||u<A)return r.copyFrom(t),B.Distance(e,t);e.subtractToRef(t,c),B.CrossToRef(s,a,l);const f=l.length();if(f<A)return r.copyFrom(t),B.Distance(e,t);l.normalizeFromLength(f);let _=c.length();if(_<A)return r.copyFrom(t),0;c.normalizeFromLength(_);const m=B.Dot(l,c),p=X.Vector3[5],g=X.Vector3[6];p.copyFrom(l).scaleInPlace(-_*m),g.copyFrom(e).addInPlace(p);const E=X.Vector3[4],T=X.Vector3[5],v=X.Vector3[7],R=X.Vector3[8];E.copyFrom(s).scaleInPlace(1/h),R.copyFrom(a).scaleInPlace(1/d),E.addInPlace(R).scaleInPlace(-1),T.copyFrom(s).scaleInPlace(-1/h),R.copyFrom(o).scaleInPlace(1/u),T.addInPlace(R).scaleInPlace(-1),v.copyFrom(o).scaleInPlace(-1/u),R.copyFrom(a).scaleInPlace(-1/d),v.addInPlace(R).scaleInPlace(-1);const S=X.Vector3[9];let I;S.copyFrom(g).subtractInPlace(t),B.CrossToRef(E,S,R),I=B.Dot(R,l);const C=I;S.copyFrom(g).subtractInPlace(i),B.CrossToRef(T,S,R),I=B.Dot(R,l);const M=I;S.copyFrom(g).subtractInPlace(n),B.CrossToRef(v,S,R),I=B.Dot(R,l);const x=I,b=X.Vector3[10];let y,O;C>0&&M<0?(b.copyFrom(s),y=t,O=i):M>0&&x<0?(b.copyFrom(o),y=i,O=n):(b.copyFrom(a).scaleInPlace(-1),y=n,O=t);const D=X.Vector3[9],N=X.Vector3[4];y.subtractToRef(g,R),O.subtractToRef(g,D),B.CrossToRef(R,D,N);if(!(B.Dot(N,l)<0))return r.copyFrom(g),Math.abs(_*m);const L=X.Vector3[5];B.CrossToRef(b,N,L),L.normalize();const F=X.Vector3[9];F.copyFrom(y).subtractInPlace(g);const w=F.length();if(w<A)return r.copyFrom(y),B.Distance(e,y);F.normalizeFromLength(w);const U=B.Dot(L,F),G=X.Vector3[7];G.copyFrom(g).addInPlace(L.scaleInPlace(w*U)),R.copyFrom(G).subtractInPlace(y),_=b.length(),b.normalizeFromLength(_);let V=B.Dot(R,b)/Math.max(_,A);return V=P(V,0,1),G.copyFrom(y).addInPlace(b.scaleInPlace(V*_)),r.copyFrom(G),B.Distance(e,G)}static Center(e,t){return B.CenterToRef(e,t,B.Zero())}static CenterToRef(e,t,i){return i.copyFromFloats((e._x+t._x)/2,(e._y+t._y)/2,(e._z+t._z)/2)}static RotationFromAxis(e,t,i){const n=new B;return B.RotationFromAxisToRef(e,t,i,n),n}static RotationFromAxisToRef(e,t,i,n){const r=X.Quaternion[0];return V.RotationQuaternionFromAxisToRef(e,t,i,r),r.toEulerAnglesToRef(n),n}}B._UpReadOnly=B.Up(),B._DownReadOnly=B.Down(),B._LeftHandedForwardReadOnly=B.Forward(!1),B._RightHandedForwardReadOnly=B.Forward(!0),B._LeftHandedBackwardReadOnly=B.Backward(!1),B._RightHandedBackwardReadOnly=B.Backward(!0),B._RightReadOnly=B.Right(),B._LeftReadOnly=B.Left(),B._ZeroReadOnly=B.Zero(),B._OneReadOnly=B.One(),Object.defineProperties(B.prototype,{dimension:{value:[3]},rank:{value:1}});class G{constructor(e=0,t=0,i=0,n=0){this.x=e,this.y=t,this.z=i,this.w=n}toString(){return`{X: ${this.x} Y: ${this.y} Z: ${this.z} W: ${this.w}}`}getClassName(){return"Vector4"}getHashCode(){let e=w(this.x);return e=397*e^w(this.y),e=397*e^w(this.z),e=397*e^w(this.w),e}asArray(){return[this.x,this.y,this.z,this.w]}toArray(e,t){return void 0===t&&(t=0),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 G.FromArrayToRef(e,t,this),this}addInPlace(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addInPlaceFromFloats(e,t,i,n){return this.x+=e,this.y+=t,this.z+=i,this.w+=n,this}add(e){return new G(this.x+e.x,this.y+e.y,this.z+e.z,this.w+e.w)}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}subtractInPlace(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subtract(e){return new G(this.x-e.x,this.y-e.y,this.z-e.z,this.w-e.w)}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}subtractFromFloats(e,t,i,n){return new G(this.x-e,this.y-t,this.z-i,this.w-n)}subtractFromFloatsToRef(e,t,i,n,r){return r.x=this.x-e,r.y=this.y-t,r.z=this.z-i,r.w=this.w-n,r}negate(){return new G(-this.x,-this.y,-this.z,-this.w)}negateInPlace(){return this.x*=-1,this.y*=-1,this.z*=-1,this.w*=-1,this}negateToRef(e){return e.x=-this.x,e.y=-this.y,e.z=-this.z,e.w=-this.w,e}scaleInPlace(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}scale(e){return new G(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}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}equals(e){return e&&this.x===e.x&&this.y===e.y&&this.z===e.z&&this.w===e.w}equalsWithEpsilon(e,t=A){return e&&O(this.x,e.x,t)&&O(this.y,e.y,t)&&O(this.z,e.z,t)&&O(this.w,e.w,t)}equalsToFloats(e,t,i,n){return this.x===e&&this.y===t&&this.z===i&&this.w===n}multiplyInPlace(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiply(e){return new G(this.x*e.x,this.y*e.y,this.z*e.z,this.w*e.w)}multiplyToRef(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}multiplyByFloats(e,t,i,n){return new G(this.x*e,this.y*t,this.z*i,this.w*n)}divide(e){return new G(this.x/e.x,this.y/e.y,this.z/e.z,this.w/e.w)}divideToRef(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}divideInPlace(e){return this.divideToRef(e,this)}minimizeInPlace(e){return e.x<this.x&&(this.x=e.x),e.y<this.y&&(this.y=e.y),e.z<this.z&&(this.z=e.z),e.w<this.w&&(this.w=e.w),this}maximizeInPlace(e){return e.x>this.x&&(this.x=e.x),e.y>this.y&&(this.y=e.y),e.z>this.z&&(this.z=e.z),e.w>this.w&&(this.w=e.w),this}minimizeInPlaceFromFloats(e,t,i,n){return this.x=Math.min(e,this.x),this.y=Math.min(t,this.y),this.z=Math.min(i,this.z),this.w=Math.min(n,this.w),this}maximizeInPlaceFromFloats(e,t,i,n){return this.x=Math.max(e,this.x),this.y=Math.max(t,this.y),this.z=Math.max(i,this.z),this.w=Math.max(n,this.w),this}floorToRef(e){return e.x=Math.floor(this.x),e.y=Math.floor(this.y),e.z=Math.floor(this.z),e.w=Math.floor(this.w),e}floor(){return new G(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 G(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 G)}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 B(this.x,this.y,this.z)}clone(){return new G(this.x,this.y,this.z,this.w)}copyFrom(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w,this}copyFromFloats(e,t,i,n){return this.x=e,this.y=t,this.z=i,this.w=n,this}set(e,t,i,n){return this.copyFromFloats(e,t,i,n)}setAll(e){return this.x=this.y=this.z=this.w=e,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}static FromArray(e,t){return t||(t=0),new G(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 G.FromArrayToRef(e,t,i),i}static FromFloatsToRef(e,t,i,n,r){return r.x=e,r.y=t,r.z=i,r.w=n,r}static Zero(){return new G(0,0,0,0)}static One(){return new G(1,1,1,1)}static Random(e=0,t=1){return new G(D(e,t),D(e,t),D(e,t),D(e,t))}static RandomToRef(e=0,t=1,i){return i.x=D(e,t),i.y=D(e,t),i.z=D(e,t),i.w=D(e,t),i}static Clamp(e,t,i){return G.ClampToRef(e,t,i,new G)}static ClampToRef(e,t,i,n){return n.x=P(e.x,t.x,i.x),n.y=P(e.y,t.y,i.y),n.z=P(e.z,t.z,i.z),n.w=P(e.w,t.w,i.w),n}static CheckExtends(e,t,i){t.minimizeInPlace(e),i.maximizeInPlace(e)}static get ZeroReadOnly(){return G._ZeroReadOnly}static Normalize(e){return G.NormalizeToRef(e,new G)}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Minimize(e,t){const i=new G;return i.copyFrom(e),i.minimizeInPlace(t),i}static Maximize(e,t){const i=new G;return i.copyFrom(e),i.maximizeInPlace(t),i}static Distance(e,t){return Math.sqrt(G.DistanceSquared(e,t))}static DistanceSquared(e,t){const i=e.x-t.x,n=e.y-t.y,r=e.z-t.z,s=e.w-t.w;return i*i+n*n+r*r+s*s}static Center(e,t){return G.CenterToRef(e,t,new G)}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 G.TransformCoordinatesToRef(e,t,new G)}static TransformCoordinatesToRef(e,t,i){return G.TransformCoordinatesFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformCoordinatesFromFloatsToRef(e,t,i,n,r){const s=n.m,a=e*s[0]+t*s[4]+i*s[8]+s[12],o=e*s[1]+t*s[5]+i*s[9]+s[13],l=e*s[2]+t*s[6]+i*s[10]+s[14],c=e*s[3]+t*s[7]+i*s[11]+s[15];return r.x=a,r.y=o,r.z=l,r.w=c,r}static TransformNormal(e,t){return G.TransformNormalToRef(e,t,new G)}static TransformNormalToRef(e,t,i){const n=t.m,r=e.x*n[0]+e.y*n[4]+e.z*n[8],s=e.x*n[1]+e.y*n[5]+e.z*n[9],a=e.x*n[2]+e.y*n[6]+e.z*n[10];return i.x=r,i.y=s,i.z=a,i.w=e.w,i}static TransformNormalFromFloatsToRef(e,t,i,n,r,s){const a=r.m;return s.x=e*a[0]+t*a[4]+i*a[8],s.y=e*a[1]+t*a[5]+i*a[9],s.z=e*a[2]+t*a[6]+i*a[10],s.w=n,s}static FromVector3(e,t=0){return new G(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}}G._ZeroReadOnly=G.Zero(),Object.defineProperties(G.prototype,{dimension:{value:[4]},rank:{value:1}});class V{get x(){return this._x}set x(e){this._x=e,this._isDirty=!0}get y(){return this._y}set y(e){this._y=e,this._isDirty=!0}get z(){return this._z}set z(e){this._z=e,this._isDirty=!0}get w(){return this._w}set w(e){this._w=e,this._isDirty=!0}constructor(e=0,t=0,i=0,n=1){this._isDirty=!0,this._x=e,this._y=t,this._z=i,this._w=n}toString(){return`{X: ${this._x} Y: ${this._y} Z: ${this._z} W: ${this._w}}`}getClassName(){return"Quaternion"}getHashCode(){let e=w(this._x);return e=397*e^w(this._y),e=397*e^w(this._z),e=397*e^w(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 V.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=A){return e&&O(this._x,e._x,t)&&O(this._y,e._y,t)&&O(this._z,e._z,t)&&O(this._w,e._w,t)}clone(){return new V(this._x,this._y,this._z,this._w)}copyFrom(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._w=e._w,this._isDirty=!0,this}copyFromFloats(e,t,i,n){return this._x=e,this._y=t,this._z=i,this._w=n,this._isDirty=!0,this}set(e,t,i,n){return this.copyFromFloats(e,t,i,n)}setAll(e){return this.copyFromFloats(e,e,e,e)}add(e){return new V(this._x+e._x,this._y+e._y,this._z+e._z,this._w+e._w)}addInPlace(e){return this._x+=e._x,this._y+=e._y,this._z+=e._z,this._w+=e._w,this._isDirty=!0,this}addToRef(e,t){return t._x=this._x+e._x,t._y=this._y+e._y,t._z=this._z+e._z,t._w=this._w+e._w,t._isDirty=!0,t}addInPlaceFromFloats(e,t,i,n){return this._x+=e,this._y+=t,this._z+=i,this._w+=n,this._isDirty=!0,this}subtractToRef(e,t){return t._x=this._x-e._x,t._y=this._y-e._y,t._z=this._z-e._z,t._w=this._w-e._w,t._isDirty=!0,t}subtractFromFloats(e,t,i,n){return this.subtractFromFloatsToRef(e,t,i,n,new V)}subtractFromFloatsToRef(e,t,i,n,r){return r._x=this._x-e,r._y=this._y-t,r._z=this._z-i,r._w=this._w-n,r._isDirty=!0,r}subtract(e){return new V(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 V(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 V(0,0,0,1);return this.multiplyToRef(e,t),t}multiplyToRef(e,t){const i=this._x*e._w+this._y*e._z-this._z*e._y+this._w*e._x,n=-this._x*e._z+this._y*e._w+this._z*e._x+this._w*e._y,r=this._x*e._y-this._y*e._x+this._z*e._w+this._w*e._z,s=-this._x*e._x-this._y*e._y-this._z*e._z+this._w*e._w;return t.copyFromFloats(i,n,r,s),t}multiplyInPlace(e){return this.multiplyToRef(e,this)}multiplyByFloats(e,t,i,n){return this._x*=e,this._y*=t,this._z*=i,this._w*=n,this._isDirty=!0,this}divide(e){throw new ReferenceError("Can not divide a quaternion")}divideToRef(e,t){throw new ReferenceError("Can not divide a quaternion")}divideInPlace(e){throw new ReferenceError("Can not divide a quaternion")}minimizeInPlace(){throw new ReferenceError("Can not minimize a quaternion")}minimizeInPlaceFromFloats(){throw new ReferenceError("Can not minimize a quaternion")}maximizeInPlace(){throw new ReferenceError("Can not maximize a quaternion")}maximizeInPlaceFromFloats(){throw new ReferenceError("Can not maximize a quaternion")}negate(){return this.negateToRef(new V)}negateInPlace(){return this._x=-this._x,this._y=-this._y,this._z=-this._z,this._w=-this._w,this._isDirty=!0,this}negateToRef(e){return e._x=-this._x,e._y=-this._y,e._z=-this._z,e._w=-this._w,e._isDirty=!0,e}equalsToFloats(e,t,i,n){return this._x===e&&this._y===t&&this._z===i&&this._w===n}floorToRef(e){throw new ReferenceError("Can not floor a quaternion")}floor(){throw new ReferenceError("Can not floor a quaternion")}fractToRef(e){throw new ReferenceError("Can not fract a quaternion")}fract(){throw new ReferenceError("Can not fract a quaternion")}conjugateToRef(e){return e.copyFromFloats(-this._x,-this._y,-this._z,this._w),e}conjugateInPlace(){return this._x*=-1,this._y*=-1,this._z*=-1,this._isDirty=!0,this}conjugate(){return new V(-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 V(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=B.Zero();return this.toEulerAnglesToRef(e),e}toEulerAnglesToRef(e){const t=this._z,i=this._x,n=this._y,r=this._w,s=n*t-i*r,a=.4999999;if(s<-a)e._y=2*Math.atan2(n,r),e._x=Math.PI/2,e._z=0,e._isDirty=!0;else if(s>a)e._y=2*Math.atan2(n,r),e._x=-Math.PI/2,e._z=0,e._isDirty=!0;else{const a=r*r,o=t*t,l=i*i,c=n*n;e._z=Math.atan2(2*(i*n+t*r),-o-l+c+a),e._x=Math.asin(-2*s),e._y=Math.atan2(2*(t*i+n*r),o-l-c+a),e._isDirty=!0}return e}toAlphaBetaGammaToRef(e){const t=this._z,i=this._x,n=this._y,r=this._w,s=Math.sqrt(i*i+n*n),a=Math.sqrt(t*t+r*r),o=2*Math.atan2(s,a),l=2*Math.atan2(t,r),c=2*Math.atan2(n,i),h=(l+c)/2,d=(l-c)/2;return e.set(d,o,h),e}toRotationMatrix(e){return k.FromQuaternionToRef(this,e),e}fromRotationMatrix(e){return V.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 V;return V.FromRotationMatrixToRef(e,t),t}static FromRotationMatrixToRef(e,t){const i=e.m,n=i[0],r=i[4],s=i[8],a=i[1],o=i[5],l=i[9],c=i[2],h=i[6],d=i[10],u=n+o+d;let f;return u>0?(f=.5/Math.sqrt(u+1),t._w=.25/f,t._x=(h-l)*f,t._y=(s-c)*f,t._z=(a-r)*f,t._isDirty=!0):n>o&&n>d?(f=2*Math.sqrt(1+n-o-d),t._w=(h-l)/f,t._x=.25*f,t._y=(r+a)/f,t._z=(s+c)/f,t._isDirty=!0):o>d?(f=2*Math.sqrt(1+o-n-d),t._w=(s-c)/f,t._x=(r+a)/f,t._y=.25*f,t._z=(l+h)/f,t._isDirty=!0):(f=2*Math.sqrt(1+d-n-o),t._w=(a-r)/f,t._x=(s+c)/f,t._y=(l+h)/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 n=V.Dot(e,t);return 1-n*n<=i}static SmoothToRef(e,t,i,n,r){let s=0===n?1:i/n;return s=P(s,0,1),V.SlerpToRef(e,t,s,r),r}static Zero(){return new V(0,0,0,0)}static Inverse(e){return new V(-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 V(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 V.RotationAxisToRef(e,t,new V)}static RotationAxisToRef(e,t,i){i._w=Math.cos(t/2);const n=Math.sin(t/2)/e.length();return i._x=e._x*n,i._y=e._y*n,i._z=e._z*n,i._isDirty=!0,i}static FromArray(e,t){return t||(t=0),new V(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t,i){return i._x=e[t],i._y=e[t+1],i._z=e[t+2],i._w=e[t+3],i._isDirty=!0,i}static FromFloatsToRef(e,t,i,n,r){return r.copyFromFloats(e,t,i,n),r}static FromEulerAngles(e,t,i){const n=new V;return V.RotationYawPitchRollToRef(t,e,i,n),n}static FromEulerAnglesToRef(e,t,i,n){return V.RotationYawPitchRollToRef(t,e,i,n),n}static FromEulerVector(e){const t=new V;return V.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromEulerVectorToRef(e,t){return V.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromUnitVectorsToRef(e,t,i,n=A){const r=B.Dot(e,t)+1;return r<n?Math.abs(e.x)>Math.abs(e.z)?i.set(-e.y,e.x,0,0):i.set(0,-e.z,e.y,0):(B.CrossToRef(e,t,H.Vector3[0]),i.set(H.Vector3[0].x,H.Vector3[0].y,H.Vector3[0].z,r)),i.normalize()}static RotationYawPitchRoll(e,t,i){const n=new V;return V.RotationYawPitchRollToRef(e,t,i,n),n}static RotationYawPitchRollToRef(e,t,i,n){const r=.5*i,s=.5*t,a=.5*e,o=Math.sin(r),l=Math.cos(r),c=Math.sin(s),h=Math.cos(s),d=Math.sin(a),u=Math.cos(a);return n._x=u*c*l+d*h*o,n._y=d*h*l-u*c*o,n._z=u*h*o-d*c*l,n._w=u*h*l+d*c*o,n._isDirty=!0,n}static RotationAlphaBetaGamma(e,t,i){const n=new V;return V.RotationAlphaBetaGammaToRef(e,t,i,n),n}static RotationAlphaBetaGammaToRef(e,t,i,n){const r=.5*(i+e),s=.5*(i-e),a=.5*t;return n._x=Math.cos(s)*Math.sin(a),n._y=Math.sin(s)*Math.sin(a),n._z=Math.sin(r)*Math.cos(a),n._w=Math.cos(r)*Math.cos(a),n._isDirty=!0,n}static RotationQuaternionFromAxis(e,t,i){const n=new V(0,0,0,0);return V.RotationQuaternionFromAxisToRef(e,t,i,n),n}static RotationQuaternionFromAxisToRef(e,t,i,n){const r=X.Matrix[0];return e=e.normalizeToRef(X.Vector3[0]),t=t.normalizeToRef(X.Vector3[1]),i=i.normalizeToRef(X.Vector3[2]),k.FromXYZAxesToRef(e,t,i,r),V.FromRotationMatrixToRef(r,n),n}static FromLookDirectionLH(e,t){const i=new V;return V.FromLookDirectionLHToRef(e,t,i),i}static FromLookDirectionLHToRef(e,t,i){const n=X.Matrix[0];return k.LookDirectionLHToRef(e,t,n),V.FromRotationMatrixToRef(n,i),i}static FromLookDirectionRH(e,t){const i=new V;return V.FromLookDirectionRHToRef(e,t,i),i}static FromLookDirectionRHToRef(e,t,i){const n=X.Matrix[0];return k.LookDirectionRHToRef(e,t,n),V.FromRotationMatrixToRef(n,i)}static Slerp(e,t,i){const n=V.Identity();return V.SlerpToRef(e,t,i,n),n}static SlerpToRef(e,t,i,n){let r,s,a=e._x*t._x+e._y*t._y+e._z*t._z+e._w*t._w,o=!1;if(a<0&&(o=!0,a=-a),a>.999999)s=1-i,r=o?-i:i;else{const e=Math.acos(a),t=1/Math.sin(e);s=Math.sin((1-i)*e)*t,r=o?-Math.sin(i*e)*t:Math.sin(i*e)*t}return n._x=s*e._x+r*t._x,n._y=s*e._y+r*t._y,n._z=s*e._z+r*t._z,n._w=s*e._w+r*t._w,n._isDirty=!0,n}static Hermite(e,t,i,n,r){const s=r*r,a=r*s,o=2*a-3*s+1,l=-2*a+3*s,c=a-2*s+r,h=a-s,d=e._x*o+i._x*l+t._x*c+n._x*h,u=e._y*o+i._y*l+t._y*c+n._y*h,f=e._z*o+i._z*l+t._z*c+n._z*h,_=e._w*o+i._w*l+t._w*c+n._w*h;return new V(d,u,f,_)}static Hermite1stDerivative(e,t,i,n,r){const s=new V;return this.Hermite1stDerivativeToRef(e,t,i,n,r,s),s}static Hermite1stDerivativeToRef(e,t,i,n,r,s){const a=r*r;return s._x=6*(a-r)*e._x+(3*a-4*r+1)*t._x+6*(-a+r)*i._x+(3*a-2*r)*n._x,s._y=6*(a-r)*e._y+(3*a-4*r+1)*t._y+6*(-a+r)*i._y+(3*a-2*r)*n._y,s._z=6*(a-r)*e._z+(3*a-4*r+1)*t._z+6*(-a+r)*i._z+(3*a-2*r)*n._z,s._w=6*(a-r)*e._w+(3*a-4*r+1)*t._w+6*(-a+r)*i._w+(3*a-2*r)*n._w,s._isDirty=!0,s}static Normalize(e){const t=V.Zero();return V.NormalizeToRef(e,t),t}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Clamp(e,t,i){const n=new V;return V.ClampToRef(e,t,i,n),n}static ClampToRef(e,t,i,n){return n.copyFromFloats(P(e.x,t.x,i.x),P(e.y,t.y,i.y),P(e.z,t.z,i.z),P(e.w,t.w,i.w))}static Random(e=0,t=1){return new V(D(e,t),D(e,t),D(e,t),D(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats(D(e,t),D(e,t),D(e,t),D(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(V.DistanceSquared(e,t))}static DistanceSquared(e,t){const i=e.x-t.x,n=e.y-t.y,r=e.z-t.z,s=e.w-t.w;return i*i+n*n+r*r+s*s}static Center(e,t){return V.CenterToRef(e,t,V.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(V.prototype,{dimension:{value:[4]},rank:{value:1}});class k{static get Use64Bits(){return b.MatrixUse64Bits}get m(){return this._m}markAsUpdated(){this.updateFlag=k._UpdateFlagSeed++,this._isIdentity=!1,this._isIdentity3x2=!1,this._isIdentityDirty=!0,this._isIdentity3x2Dirty=!0}_updateIdentityStatus(e,t=!1,i=!1,n=!0){this._isIdentity=e,this._isIdentity3x2=e||i,this._isIdentityDirty=!this._isIdentity&&t,this._isIdentity3x2Dirty=!this._isIdentity3x2&&n}constructor(){this._isIdentity=!1,this._isIdentityDirty=!0,this._isIdentity3x2=!0,this._isIdentity3x2Dirty=!0,this.updateFlag=-1,b.MatrixTrackPrecisionChange&&b.MatrixTrackedMatrices.push(this),this._m=new b.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],n=e[2],r=e[3],s=e[4],a=e[5],o=e[6],l=e[7],c=e[8],h=e[9],d=e[10],u=e[11],f=e[12],_=e[13],m=e[14],p=e[15],g=d*p-m*u,E=h*p-_*u,T=h*m-_*d,A=c*p-f*u,v=c*m-d*f,R=c*_-f*h;return t*+(a*g-o*E+l*T)+i*-(s*g-o*A+l*v)+n*+(s*E-a*A+l*R)+r*-(s*T-a*v+o*R)}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 n=0;n<16;n++)e[t+n]=i[n];return this}asArray(){return this._m}fromArray(e,t=0){return k.FromArrayToRef(e,t,this)}copyFromFloats(...e){return k.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 k.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 k;return this.addToRef(e,t),t}addToRef(e,t){const i=this._m,n=t._m,r=e.m;for(let e=0;e<16;e++)n[e]=i[e]+r[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,n=e.m,r=t._m;for(let e=0;e<16;e++)r[e]=i[e]-n[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 k)}subtractFromFloatsToRef(...e){const t=e.pop(),i=this._m,n=t._m,r=e;for(let e=0;e<16;e++)n[e]=i[e]-r[e];return t.markAsUpdated(),t}invertToRef(e){if(!0===this._isIdentity)return k.IdentityToRef(e),e;const t=this._m,i=t[0],n=t[1],r=t[2],s=t[3],a=t[4],o=t[5],l=t[6],c=t[7],h=t[8],d=t[9],u=t[10],f=t[11],_=t[12],m=t[13],p=t[14],g=t[15],E=u*g-p*f,T=d*g-m*f,A=d*p-m*u,v=h*g-_*f,R=h*p-u*_,S=h*m-_*d,I=+(o*E-l*T+c*A),C=-(a*E-l*v+c*R),M=+(a*T-o*v+c*S),x=-(a*A-o*R+l*S),b=i*I+n*C+r*M+s*x;if(0===b)return e.copyFrom(this),e;const y=1/b,O=l*g-p*c,D=o*g-m*c,N=o*p-m*l,P=a*g-_*c,L=a*p-_*l,F=a*m-_*o,w=l*f-u*c,U=o*f-d*c,B=o*u-d*l,G=a*f-h*c,V=a*u-h*l,X=a*d-h*o,H=-(n*E-r*T+s*A),W=+(i*E-r*v+s*R),z=-(i*T-n*v+s*S),Y=+(i*A-n*R+r*S),K=+(n*O-r*D+s*N),q=-(i*O-r*P+s*L),j=+(i*D-n*P+s*F),Q=-(i*N-n*L+r*F),Z=-(n*w-r*U+s*B),J=+(i*w-r*G+s*V),$=-(i*U-n*G+s*X),ee=+(i*B-n*V+r*X);return k.FromValuesToRef(I*y,H*y,K*y,Z*y,C*y,W*y,q*y,J*y,M*y,z*y,j*y,$*y,x*y,Y*y,Q*y,ee*y,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 B(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 k.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 k;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,n=t._m,r=e;for(let e=0;e<16;e++)n[e]=i[e]*r[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 n=this._m,r=e.m,s=n[0],a=n[1],o=n[2],l=n[3],c=n[4],h=n[5],d=n[6],u=n[7],f=n[8],_=n[9],m=n[10],p=n[11],g=n[12],E=n[13],T=n[14],A=n[15],v=r[0],R=r[1],S=r[2],I=r[3],C=r[4],M=r[5],x=r[6],b=r[7],y=r[8],O=r[9],D=r[10],N=r[11],P=r[12],L=r[13],F=r[14],w=r[15];return t[i]=s*v+a*C+o*y+l*P,t[i+1]=s*R+a*M+o*O+l*L,t[i+2]=s*S+a*x+o*D+l*F,t[i+3]=s*I+a*b+o*N+l*w,t[i+4]=c*v+h*C+d*y+u*P,t[i+5]=c*R+h*M+d*O+u*L,t[i+6]=c*S+h*x+d*D+u*F,t[i+7]=c*I+h*b+d*N+u*w,t[i+8]=f*v+_*C+m*y+p*P,t[i+9]=f*R+_*M+m*O+p*L,t[i+10]=f*S+_*x+m*D+p*F,t[i+11]=f*I+_*b+m*N+p*w,t[i+12]=g*v+E*C+T*y+A*P,t[i+13]=g*R+E*M+T*O+A*L,t[i+14]=g*S+E*x+T*D+A*F,t[i+15]=g*I+E*b+T*N+A*w,this}divide(e){return this.divideToRef(e,new k)}divideToRef(e,t){const i=this._m,n=e.m,r=t._m;for(let e=0;e<16;e++)r[e]=i[e]/n[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 k)}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,n=t.m;return i[0]===n[0]&&i[1]===n[1]&&i[2]===n[2]&&i[3]===n[3]&&i[4]===n[4]&&i[5]===n[5]&&i[6]===n[6]&&i[7]===n[7]&&i[8]===n[8]&&i[9]===n[9]&&i[10]===n[10]&&i[11]===n[11]&&i[12]===n[12]&&i[13]===n[13]&&i[14]===n[14]&&i[15]===n[15]}equalsWithEpsilon(e,t=0){const i=this._m,n=e.m;for(let e=0;e<16;e++)if(!O(i[e],n[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 k)}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 k)}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 k;return e.copyFrom(this),e}getClassName(){return"Matrix"}getHashCode(){let e=w(this._m[0]);for(let t=1;t<16;t++)e=397*e^w(this._m[t]);return e}decomposeToTransformNode(e){return e.rotationQuaternion=e.rotationQuaternion||new V,this.decompose(e.scaling,e.rotationQuaternion,e.position)}decompose(e,t,i,n,r=!0){if(this._isIdentity)return i&&i.setAll(0),e&&e.setAll(1),t&&t.copyFromFloats(0,0,0,1),!0;const s=this._m;if(i&&i.copyFromFloats(s[12],s[13],s[14]),(e=e||X.Vector3[0]).x=Math.sqrt(s[0]*s[0]+s[1]*s[1]+s[2]*s[2]),e.y=Math.sqrt(s[4]*s[4]+s[5]*s[5]+s[6]*s[6]),e.z=Math.sqrt(s[8]*s[8]+s[9]*s[9]+s[10]*s[10]),n){const t=(r?n.absoluteScaling.x:n.scaling.x)<0?-1:1,i=(r?n.absoluteScaling.y:n.scaling.y)<0?-1:1,s=(r?n.absoluteScaling.z:n.scaling.z)<0?-1:1;e.x*=t,e.y*=i,e.z*=s}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,n=1/e._y,r=1/e._z;k.FromValuesToRef(s[0]*i,s[1]*i,s[2]*i,0,s[4]*n,s[5]*n,s[6]*n,0,s[8]*r,s[9]*r,s[10]*r,0,0,0,0,1,X.Matrix[0]),V.FromRotationMatrixToRef(X.Matrix[0],t)}return!0}getRow(e){if(e<0||e>3)return null;const t=4*e;return new G(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 k;return k.TransposeToRef(this,e),e}transposeToRef(e){return k.TransposeToRef(this,e),e}setRowFromFloats(e,t,i,n,r){if(e<0||e>3)return this;const s=4*e;return this._m[s+0]=t,this._m[s+1]=i,this._m[s+2]=n,this._m[s+3]=r,this.markAsUpdated(),this}scale(e){const t=new k;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=X.Matrix[0];this.invertToRef(t),t.transposeToRef(e);const i=e._m;return k.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 k;return this.getRotationMatrixToRef(e),e}getRotationMatrixToRef(e){const t=X.Vector3[0];if(!this.decompose(t))return k.IdentityToRef(e),e;const i=this._m,n=1/t._x,r=1/t._y,s=1/t._z;return k.FromValuesToRef(i[0]*n,i[1]*n,i[2]*n,0,i[4]*r,i[5]*r,i[6]*r,0,i[8]*s,i[9]*s,i[10]*s,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 k;return k.FromArrayToRef(e,t,i),i}static FromArrayToRef(e,t,i){for(let n=0;n<16;n++)i._m[n]=e[n+t];return i.markAsUpdated(),i}static FromFloat32ArrayToRefScaled(e,t,i,n){return n._m[0]=e[0+t]*i,n._m[1]=e[1+t]*i,n._m[2]=e[2+t]*i,n._m[3]=e[3+t]*i,n._m[4]=e[4+t]*i,n._m[5]=e[5+t]*i,n._m[6]=e[6+t]*i,n._m[7]=e[7+t]*i,n._m[8]=e[8+t]*i,n._m[9]=e[9+t]*i,n._m[10]=e[10+t]*i,n._m[11]=e[11+t]*i,n._m[12]=e[12+t]*i,n._m[13]=e[13+t]*i,n._m[14]=e[14+t]*i,n._m[15]=e[15+t]*i,n.markAsUpdated(),n}static get IdentityReadOnly(){return k._IdentityReadOnly}static FromValuesToRef(e,t,i,n,r,s,a,o,l,c,h,d,u,f,_,m,p){const g=p._m;g[0]=e,g[1]=t,g[2]=i,g[3]=n,g[4]=r,g[5]=s,g[6]=a,g[7]=o,g[8]=l,g[9]=c,g[10]=h,g[11]=d,g[12]=u,g[13]=f,g[14]=_,g[15]=m,p.markAsUpdated()}static FromValues(e,t,i,n,r,s,a,o,l,c,h,d,u,f,_,m){const p=new k,g=p._m;return g[0]=e,g[1]=t,g[2]=i,g[3]=n,g[4]=r,g[5]=s,g[6]=a,g[7]=o,g[8]=l,g[9]=c,g[10]=h,g[11]=d,g[12]=u,g[13]=f,g[14]=_,g[15]=m,p.markAsUpdated(),p}static Compose(e,t,i){const n=new k;return k.ComposeToRef(e,t,i,n),n}static ComposeToRef(e,t,i,n){const r=n._m,s=t._x,a=t._y,o=t._z,l=t._w,c=s+s,h=a+a,d=o+o,u=s*c,f=s*h,_=s*d,m=a*h,p=a*d,g=o*d,E=l*c,T=l*h,A=l*d,v=e._x,R=e._y,S=e._z;return r[0]=(1-(m+g))*v,r[1]=(f+A)*v,r[2]=(_-T)*v,r[3]=0,r[4]=(f-A)*R,r[5]=(1-(u+g))*R,r[6]=(p+E)*R,r[7]=0,r[8]=(_+T)*S,r[9]=(p-E)*S,r[10]=(1-(u+m))*S,r[11]=0,r[12]=i._x,r[13]=i._y,r[14]=i._z,r[15]=1,n.markAsUpdated(),n}static Identity(){const e=k.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 k.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=k.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 k;return k.RotationXToRef(e,t),t}static Invert(e){const t=new k;return e.invertToRef(t),t}static RotationXToRef(e,t){const i=Math.sin(e),n=Math.cos(e);return k.FromValuesToRef(1,0,0,0,0,n,i,0,0,-i,n,0,0,0,0,1,t),t._updateIdentityStatus(1===n&&0===i),t}static RotationY(e){const t=new k;return k.RotationYToRef(e,t),t}static RotationYToRef(e,t){const i=Math.sin(e),n=Math.cos(e);return k.FromValuesToRef(n,0,-i,0,0,1,0,0,i,0,n,0,0,0,0,1,t),t._updateIdentityStatus(1===n&&0===i),t}static RotationZ(e){const t=new k;return k.RotationZToRef(e,t),t}static RotationZToRef(e,t){const i=Math.sin(e),n=Math.cos(e);return k.FromValuesToRef(n,i,0,0,-i,n,0,0,0,0,1,0,0,0,0,1,t),t._updateIdentityStatus(1===n&&0===i),t}static RotationAxis(e,t){const i=new k;return k.RotationAxisToRef(e,t,i),i}static RotationAxisToRef(e,t,i){const n=Math.sin(-t),r=Math.cos(-t),s=1-r;e=e.normalizeToRef(X.Vector3[0]);const a=i._m;return a[0]=e._x*e._x*s+r,a[1]=e._x*e._y*s-e._z*n,a[2]=e._x*e._z*s+e._y*n,a[3]=0,a[4]=e._y*e._x*s+e._z*n,a[5]=e._y*e._y*s+r,a[6]=e._y*e._z*s-e._x*n,a[7]=0,a[8]=e._z*e._x*s-e._y*n,a[9]=e._z*e._y*s+e._x*n,a[10]=e._z*e._z*s+r,a[11]=0,a[12]=0,a[13]=0,a[14]=0,a[15]=1,i.markAsUpdated(),i}static RotationAlignToRef(e,t,i,n=!1){const r=B.Dot(t,e),s=i._m;if(r<-1+A)s[0]=-1,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=n?1:-1,s[6]=0,s[7]=0,s[8]=0,s[9]=0,s[10]=n?-1:1,s[11]=0;else{const i=B.Cross(t,e),n=1/(1+r);s[0]=i._x*i._x*n+r,s[1]=i._y*i._x*n-i._z,s[2]=i._z*i._x*n+i._y,s[3]=0,s[4]=i._x*i._y*n+i._z,s[5]=i._y*i._y*n+r,s[6]=i._z*i._y*n-i._x,s[7]=0,s[8]=i._x*i._z*n-i._y,s[9]=i._y*i._z*n+i._x,s[10]=i._z*i._z*n+r,s[11]=0}return s[12]=0,s[13]=0,s[14]=0,s[15]=1,i.markAsUpdated(),i}static RotationYawPitchRoll(e,t,i){const n=new k;return k.RotationYawPitchRollToRef(e,t,i,n),n}static RotationYawPitchRollToRef(e,t,i,n){return V.RotationYawPitchRollToRef(e,t,i,X.Quaternion[0]),X.Quaternion[0].toRotationMatrix(n),n}static Scaling(e,t,i){const n=new k;return k.ScalingToRef(e,t,i,n),n}static ScalingToRef(e,t,i,n){return k.FromValuesToRef(e,0,0,0,0,t,0,0,0,0,i,0,0,0,0,1,n),n._updateIdentityStatus(1===e&&1===t&&1===i),n}static Translation(e,t,i){const n=new k;return k.TranslationToRef(e,t,i,n),n}static TranslationToRef(e,t,i,n){return k.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,e,t,i,1,n),n._updateIdentityStatus(0===e&&0===t&&0===i),n}static Lerp(e,t,i){const n=new k;return k.LerpToRef(e,t,i,n),n}static LerpToRef(e,t,i,n){const r=n._m,s=e.m,a=t.m;for(let e=0;e<16;e++)r[e]=s[e]*(1-i)+a[e]*i;return n.markAsUpdated(),n}static DecomposeLerp(e,t,i){const n=new k;return k.DecomposeLerpToRef(e,t,i,n),n}static DecomposeLerpToRef(e,t,i,n){const r=X.Vector3[0],s=X.Quaternion[0],a=X.Vector3[1];e.decompose(r,s,a);const o=X.Vector3[2],l=X.Quaternion[1],c=X.Vector3[3];t.decompose(o,l,c);const h=X.Vector3[4];B.LerpToRef(r,o,i,h);const d=X.Quaternion[2];V.SlerpToRef(s,l,i,d);const u=X.Vector3[5];return B.LerpToRef(a,c,i,u),k.ComposeToRef(h,d,u,n),n}static LookAtLH(e,t,i){const n=new k;return k.LookAtLHToRef(e,t,i,n),n}static LookAtLHToRef(e,t,i,n){const r=X.Vector3[0],s=X.Vector3[1],a=X.Vector3[2];t.subtractToRef(e,a),a.normalize(),B.CrossToRef(i,a,r);const o=r.lengthSquared();0===o?r.x=1:r.normalizeFromLength(Math.sqrt(o)),B.CrossToRef(a,r,s),s.normalize();const l=-B.Dot(r,e),c=-B.Dot(s,e),h=-B.Dot(a,e);return k.FromValuesToRef(r._x,s._x,a._x,0,r._y,s._y,a._y,0,r._z,s._z,a._z,0,l,c,h,1,n),n}static LookAtRH(e,t,i){const n=new k;return k.LookAtRHToRef(e,t,i,n),n}static LookAtRHToRef(e,t,i,n){const r=X.Vector3[0],s=X.Vector3[1],a=X.Vector3[2];e.subtractToRef(t,a),a.normalize(),B.CrossToRef(i,a,r);const o=r.lengthSquared();0===o?r.x=1:r.normalizeFromLength(Math.sqrt(o)),B.CrossToRef(a,r,s),s.normalize();const l=-B.Dot(r,e),c=-B.Dot(s,e),h=-B.Dot(a,e);return k.FromValuesToRef(r._x,s._x,a._x,0,r._y,s._y,a._y,0,r._z,s._z,a._z,0,l,c,h,1,n),n}static LookDirectionLH(e,t){const i=new k;return k.LookDirectionLHToRef(e,t,i),i}static LookDirectionLHToRef(e,t,i){const n=X.Vector3[0];n.copyFrom(e),n.scaleInPlace(-1);const r=X.Vector3[1];return B.CrossToRef(t,n,r),k.FromValuesToRef(r._x,r._y,r._z,0,t._x,t._y,t._z,0,n._x,n._y,n._z,0,0,0,0,1,i),i}static LookDirectionRH(e,t){const i=new k;return k.LookDirectionRHToRef(e,t,i),i}static LookDirectionRHToRef(e,t,i){const n=X.Vector3[2];return B.CrossToRef(t,e,n),k.FromValuesToRef(n._x,n._y,n._z,0,t._x,t._y,t._z,0,e._x,e._y,e._z,0,0,0,0,1,i),i}static OrthoLH(e,t,i,n,r){const s=new k;return k.OrthoLHToRef(e,t,i,n,s,r),s}static OrthoLHToRef(e,t,i,n,r,s){const a=2/e,o=2/t,l=2/(n-i),c=-(n+i)/(n-i);return k.FromValuesToRef(a,0,0,0,0,o,0,0,0,0,l,0,0,0,c,1,r),s&&r.multiplyToRef(W,r),r._updateIdentityStatus(1===a&&1===o&&1===l&&0===c),r}static OrthoOffCenterLH(e,t,i,n,r,s,a){const o=new k;return k.OrthoOffCenterLHToRef(e,t,i,n,r,s,o,a),o}static OrthoOffCenterLHToRef(e,t,i,n,r,s,a,o){const l=2/(t-e),c=2/(n-i),h=2/(s-r),d=-(s+r)/(s-r),u=(e+t)/(e-t),f=(n+i)/(i-n);return k.FromValuesToRef(l,0,0,0,0,c,0,0,0,0,h,0,u,f,d,1,a),o&&a.multiplyToRef(W,a),a.markAsUpdated(),a}static ObliqueOffCenterLHToRef(e,t,i,n,r,s,a,o,l,c,h){const d=-a*Math.cos(o),u=-a*Math.sin(o);return k.TranslationToRef(0,0,-l,X.Matrix[1]),k.FromValuesToRef(1,0,0,0,0,1,0,0,d,u,1,0,0,0,0,1,X.Matrix[0]),X.Matrix[1].multiplyToRef(X.Matrix[0],X.Matrix[0]),k.TranslationToRef(0,0,l,X.Matrix[1]),X.Matrix[0].multiplyToRef(X.Matrix[1],X.Matrix[0]),k.OrthoOffCenterLHToRef(e,t,i,n,r,s,c,h),X.Matrix[0].multiplyToRef(c,c),c}static OrthoOffCenterRH(e,t,i,n,r,s,a){const o=new k;return k.OrthoOffCenterRHToRef(e,t,i,n,r,s,o,a),o}static OrthoOffCenterRHToRef(e,t,i,n,r,s,a,o){return k.OrthoOffCenterLHToRef(e,t,i,n,r,s,a,o),a._m[10]*=-1,a}static ObliqueOffCenterRHToRef(e,t,i,n,r,s,a,o,l,c,h){const d=a*Math.cos(o),u=a*Math.sin(o);return k.TranslationToRef(0,0,l,X.Matrix[1]),k.FromValuesToRef(1,0,0,0,0,1,0,0,d,u,1,0,0,0,0,1,X.Matrix[0]),X.Matrix[1].multiplyToRef(X.Matrix[0],X.Matrix[0]),k.TranslationToRef(0,0,-l,X.Matrix[1]),X.Matrix[0].multiplyToRef(X.Matrix[1],X.Matrix[0]),k.OrthoOffCenterRHToRef(e,t,i,n,r,s,c,h),X.Matrix[0].multiplyToRef(c,c),c}static PerspectiveLH(e,t,i,n,r,s=0){const a=new k,o=2*i/e,l=2*i/t,c=(n+i)/(n-i),h=-2*n*i/(n-i),d=Math.tan(s);return k.FromValuesToRef(o,0,0,0,0,l,0,d,0,0,c,1,0,0,h,0,a),r&&a.multiplyToRef(W,a),a._updateIdentityStatus(!1),a}static PerspectiveFovLH(e,t,i,n,r,s=0,a=!1){const o=new k;return k.PerspectiveFovLHToRef(e,t,i,n,o,!0,r,s,a),o}static PerspectiveFovLHToRef(e,t,i,n,r,s=!0,a,o=0,l=!1){const c=i,h=n,d=1/Math.tan(.5*e),u=s?d/t:d,f=s?d:d*t,_=l&&0===c?-1:0!==h?(h+c)/(h-c):1,m=l&&0===c?2*h:0!==h?-2*h*c/(h-c):-2*c,p=Math.tan(o);return k.FromValuesToRef(u,0,0,0,0,f,0,p,0,0,_,1,0,0,m,0,r),a&&r.multiplyToRef(W,r),r._updateIdentityStatus(!1),r}static PerspectiveFovReverseLHToRef(e,t,i,n,r,s=!0,a,o=0){const l=1/Math.tan(.5*e),c=s?l/t:l,h=s?l:l*t,d=Math.tan(o);return k.FromValuesToRef(c,0,0,0,0,h,0,d,0,0,-i,1,0,0,1,0,r),a&&r.multiplyToRef(W,r),r._updateIdentityStatus(!1),r}static PerspectiveFovRH(e,t,i,n,r,s=0,a=!1){const o=new k;return k.PerspectiveFovRHToRef(e,t,i,n,o,!0,r,s,a),o}static PerspectiveFovRHToRef(e,t,i,n,r,s=!0,a,o=0,l=!1){const c=i,h=n,d=1/Math.tan(.5*e),u=s?d/t:d,f=s?d:d*t,_=l&&0===c?1:0!==h?-(h+c)/(h-c):-1,m=l&&0===c?2*h:0!==h?-2*h*c/(h-c):-2*c,p=Math.tan(o);return k.FromValuesToRef(u,0,0,0,0,f,0,p,0,0,_,-1,0,0,m,0,r),a&&r.multiplyToRef(W,r),r._updateIdentityStatus(!1),r}static PerspectiveFovReverseRHToRef(e,t,i,n,r,s=!0,a,o=0){const l=1/Math.tan(.5*e),c=s?l/t:l,h=s?l:l*t,d=Math.tan(o);return k.FromValuesToRef(c,0,0,0,0,h,0,d,0,0,-i,-1,0,0,-1,0,r),a&&r.multiplyToRef(W,r),r._updateIdentityStatus(!1),r}static GetFinalMatrix(e,t,i,n,r,s){const a=e.width,o=e.height,l=e.x,c=e.y,h=k.FromValues(a/2,0,0,0,0,-o/2,0,0,0,0,s-r,0,l+a/2,o/2+c,r,1),d=new k;return t.multiplyToRef(i,d),d.multiplyToRef(n,d),d.multiplyToRef(h,d)}static GetAsMatrix2x2(e){const t=e.m,i=[t[0],t[1],t[4],t[5]];return b.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 b.MatrixUse64Bits?i:new Float32Array(i)}static Transpose(e){const t=new k;return k.TransposeToRef(e,t),t}static TransposeToRef(e,t){const i=e.m,n=i[0],r=i[4],s=i[8],a=i[12],o=i[1],l=i[5],c=i[9],h=i[13],d=i[2],u=i[6],f=i[10],_=i[14],m=i[3],p=i[7],g=i[11],E=i[15],T=t._m;return T[0]=n,T[1]=r,T[2]=s,T[3]=a,T[4]=o,T[5]=l,T[6]=c,T[7]=h,T[8]=d,T[9]=u,T[10]=f,T[11]=_,T[12]=m,T[13]=p,T[14]=g,T[15]=E,t.markAsUpdated(),t._updateIdentityStatus(e._isIdentity,e._isIdentityDirty),t}static Reflection(e){const t=new k;return k.ReflectionToRef(e,t),t}static ReflectionToRef(e,t){e.normalize();const i=e.normal.x,n=e.normal.y,r=e.normal.z,s=-2*i,a=-2*n,o=-2*r;return k.FromValuesToRef(s*i+1,a*i,o*i,0,s*n,a*n+1,o*n,0,s*r,a*r,o*r+1,0,s*e.d,a*e.d,o*e.d,1,t),t}static FromXYZAxesToRef(e,t,i,n){return k.FromValuesToRef(e._x,e._y,e._z,0,t._x,t._y,t._z,0,i._x,i._y,i._z,0,0,0,0,1,n),n}static FromQuaternionToRef(e,t){const i=e._x*e._x,n=e._y*e._y,r=e._z*e._z,s=e._x*e._y,a=e._z*e._w,o=e._z*e._x,l=e._y*e._w,c=e._y*e._z,h=e._x*e._w;return t._m[0]=1-2*(n+r),t._m[1]=2*(s+a),t._m[2]=2*(o-l),t._m[3]=0,t._m[4]=2*(s-a),t._m[5]=1-2*(r+i),t._m[6]=2*(c+h),t._m[7]=0,t._m[8]=2*(o+l),t._m[9]=2*(c-h),t._m[10]=1-2*(n+i),t._m[11]=0,t._m[12]=0,t._m[13]=0,t._m[14]=0,t._m[15]=1,t.markAsUpdated(),t}}k._UpdateFlagSeed=0,k._IdentityReadOnly=k.Identity(),Object.defineProperties(k.prototype,{dimension:{value:[4,4]},rank:{value:2}});class X{}X.Vector3=R(11,B.Zero),X.Matrix=R(2,k.Identity),X.Quaternion=R(3,V.Zero);class H{}H.Vector2=R(3,U.Zero),H.Vector3=R(13,B.Zero),H.Vector4=R(3,G.Zero),H.Quaternion=R(3,V.Zero),H.Matrix=R(8,k.Identity),M("BABYLON.Vector2",U),M("BABYLON.Vector3",B),M("BABYLON.Vector4",G),M("BABYLON.Matrix",k);const W=k.FromValues(1,0,0,0,0,1,0,0,0,0,.5,0,0,0,.5,1),z={};function Y(e,t=!1){if(!t||!z[e])return z[e]=!0,`${e} needs to be imported before as it contains a side-effect required by your code.`}class K{static Eval(e,t){return"true"===(e=e.match(/\([^()]*\)/g)?e.replace(/\([^()]*\)/g,(e=>(e=e.slice(1,e.length-1),K._HandleParenthesisContent(e,t)))):K._HandleParenthesisContent(e,t))||"false"!==e&&K.Eval(e,t)}static _HandleParenthesisContent(e,t){let i;t=t||(e=>"true"===e);const n=e.split("||");for(const e in n)if(Object.prototype.hasOwnProperty.call(n,e)){let r=K._SimplifyNegation(n[e].trim());const s=r.split("&&");if(s.length>1)for(let e=0;e<s.length;++e){const n=K._SimplifyNegation(s[e].trim());if(i="true"!==n&&"false"!==n?"!"===n[0]?!t(n.substring(1)):t(n):"true"===n,!i){r="false";break}}if(i||"true"===r){i=!0;break}i="true"!==r&&"false"!==r?"!"===r[0]?!t(r.substring(1)):t(r):"true"===r}return i?"true":"false"}static _SimplifyNegation(e){return"!true"===(e=(e=e.replace(/^[\s!]+/,(e=>(e=e.replace(/[\s]/g,(()=>""))).length%2?"!":""))).trim())?e="false":"!false"===e&&(e="true"),e}}class q{static EnableFor(e){e._tags=e._tags||{},e.hasTags=()=>q.HasTags(e),e.addTags=t=>q.AddTagsTo(e,t),e.removeTags=t=>q.RemoveTagsFrom(e,t),e.matchesTagsQuery=t=>q.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){if(!t)return;if("string"!=typeof t)return;t.split(" ").forEach((function(t){q._AddTagTo(e,t)}))}static _AddTagTo(e,t){""!==(t=t.trim())&&"true"!==t&&"false"!==t&&(t.match(/[\s]/)||t.match(/^([!]|([|]|[&]){2})/)||(q.EnableFor(e),e._tags[t]=!0))}static RemoveTagsFrom(e,t){if(!q.HasTags(e))return;const i=t.split(" ");for(const t in i)q._RemoveTagFrom(e,i[t])}static _RemoveTagFrom(e,t){delete e._tags[t]}static MatchesQuery(e,t){return void 0===t||(""===t?q.HasTags(e):K.Eval(t,(t=>q.HasTags(e)&&e._tags[t])))}}class j{static Sign(e){return 0===(e=+e)||isNaN(e)?e:e>0?1:-1}static Log2(e){return Math.log(e)*Math.LOG2E}static ILog2(e){if(Math.log2)return Math.floor(Math.log2(e));if(e<0)return NaN;if(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}static Repeat(e,t){return e-Math.floor(e/t)*t}static Normalize(e,t,i){return(e-t)/(i-t)}static Denormalize(e,t,i){return e*(i-t)+t}static DeltaAngle(e,t){let i=j.Repeat(t-e,360);return i>180&&(i-=360),i}static PingPong(e,t){const i=j.Repeat(e,2*t);return t-Math.abs(i-t)}static SmoothStep(e,t,i){let n=j.Clamp(i);return n=-2*n*n*n+3*n*n,t*n+e*(1-n)}static MoveTowards(e,t,i){let n=0;return n=Math.abs(t-e)<=i?t:e+j.Sign(t-e)*i,n}static MoveTowardsAngle(e,t,i){const n=j.DeltaAngle(e,t);let r=0;return-i<n&&n<i?r=t:(t=e+n,r=j.MoveTowards(e,t,i)),r}static LerpAngle(e,t,i){let n=j.Repeat(t-e,360);return n>180&&(n-=360),e+n*P(i)}static InverseLerp(e,t,i){let n=0;return n=e!=t?P((i-e)/(t-e)):0,n}static Hermite(e,t,i,n,r){const s=r*r,a=r*s;return e*(2*a-3*s+1)+i*(-2*a+3*s)+t*(a-2*s+r)+n*(a-s)}static Hermite1stDerivative(e,t,i,n,r){const s=r*r;return 6*(s-r)*e+(3*s-4*r+1)*t+6*(-s+r)*i+(3*s-2*r)*n}static RangeToPercent(e,t,i){return(e-t)/(i-t)}static PercentToRange(e,t,i){return(i-t)*e+t}static HCF(e,t){const i=e%t;return 0===i?t:j.HCF(t,i)}}function Q(e){return Math.pow(e,T)}function Z(e){return e<=.04045?.0773993808*e:Math.pow(.947867299*(e+.055),2.4)}function J(e){return Math.pow(e,E)}function $(e){return e<=.0031308?12.92*e:1.055*Math.pow(e,.41666)-.055}j.TwoPi=2*Math.PI,j.WithinEpsilon=O,j.ToHex=F,j.Clamp=P,j.Lerp=N,j.RandomRange=D,j.NormalizeRadians=L;class ee{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 ee.FromArrayToRef(e,t,this),this}toColor4(e=1){return new te(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 ee(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 ee(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=A){return j.WithinEpsilon(this.r,e.r,t)&&j.WithinEpsilon(this.g,e.g,t)&&j.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 ee(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=P(this.r,e,t),i.g=P(this.g,e,t),i.b=P(this.b,e,t),i}add(e){return new ee(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 ee(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 ee(this.r-e,this.g-t,this.b-i)}subtractFromFloatsToRef(e,t,i,n){return n.r=this.r-e,n.g=this.g-t,n.b=this.b-i,n}clone(){return new ee(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"#"+F(e)+F(t)+F(i)}toHSV(){return this.toHSVToRef(new ee)}toHSVToRef(e){const t=this.r,i=this.g,n=this.b,r=Math.max(t,i,n),s=Math.min(t,i,n);let a=0,o=0;const l=r,c=r-s;return 0!==r&&(o=c/r),r!=s&&(r==t?(a=(i-n)/c,i<n&&(a+=6)):r==i?a=(n-t)/c+2:r==n&&(a=(t-i)/c+4),a*=60),e.r=a,e.g=o,e.b=l,e}toLinearSpace(e=!1){const t=new ee;return this.toLinearSpaceToRef(t,e),t}toLinearSpaceToRef(e,t=!1){return t?(e.r=Z(this.r),e.g=Z(this.g),e.b=Z(this.b)):(e.r=Q(this.r),e.g=Q(this.g),e.b=Q(this.b)),this}toGammaSpace(e=!1){const t=new ee;return this.toGammaSpaceToRef(t,e),t}toGammaSpaceToRef(e,t=!1){return t?(e.r=$(this.r),e.g=$(this.g),e.b=$(this.b)):(e.r=J(this.r),e.g=J(this.g),e.b=J(this.b)),this}static HSVtoRGBToRef(e,t,i,n){const r=i*t,s=e/60,a=r*(1-Math.abs(s%2-1));let o=0,l=0,c=0;s>=0&&s<=1?(o=r,l=a):s>=1&&s<=2?(o=a,l=r):s>=2&&s<=3?(l=r,c=a):s>=3&&s<=4?(l=a,c=r):s>=4&&s<=5?(o=a,c=r):s>=5&&s<=6&&(o=r,c=a);const h=i-r;return n.r=o+h,n.g=l+h,n.b=c+h,n}static FromHSV(e,t,i){const n=new ee(0,0,0);return ee.HSVtoRGBToRef(e,t,i,n),n}static FromHexString(e){if("#"!==e.substring(0,1)||7!==e.length)return new ee(0,0,0);const t=parseInt(e.substring(1,3),16),i=parseInt(e.substring(3,5),16),n=parseInt(e.substring(5,7),16);return ee.FromInts(t,i,n)}static FromArray(e,t=0){return new ee(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 ee(e/255,t/255,i/255)}static Lerp(e,t,i){const n=new ee(0,0,0);return ee.LerpToRef(e,t,i,n),n}static LerpToRef(e,t,i,n){n.r=e.r+(t.r-e.r)*i,n.g=e.g+(t.g-e.g)*i,n.b=e.b+(t.b-e.b)*i}static Hermite(e,t,i,n,r){const s=r*r,a=r*s,o=2*a-3*s+1,l=-2*a+3*s,c=a-2*s+r,h=a-s,d=e.r*o+i.r*l+t.r*c+n.r*h,u=e.g*o+i.g*l+t.g*c+n.g*h,f=e.b*o+i.b*l+t.b*c+n.b*h;return new ee(d,u,f)}static Hermite1stDerivative(e,t,i,n,r){const s=ee.Black();return this.Hermite1stDerivativeToRef(e,t,i,n,r,s),s}static Hermite1stDerivativeToRef(e,t,i,n,r,s){const a=r*r;s.r=6*(a-r)*e.r+(3*a-4*r+1)*t.r+6*(-a+r)*i.r+(3*a-2*r)*n.r,s.g=6*(a-r)*e.g+(3*a-4*r+1)*t.g+6*(-a+r)*i.g+(3*a-2*r)*n.g,s.b=6*(a-r)*e.b+(3*a-4*r+1)*t.b+6*(-a+r)*i.b+(3*a-2*r)*n.b}static Red(){return new ee(1,0,0)}static Green(){return new ee(0,1,0)}static Blue(){return new ee(0,0,1)}static Black(){return new ee(0,0,0)}static get BlackReadOnly(){return ee._BlackReadOnly}static White(){return new ee(1,1,1)}static Purple(){return new ee(.5,0,.5)}static Magenta(){return new ee(1,0,1)}static Yellow(){return new ee(1,1,0)}static Gray(){return new ee(.5,.5,.5)}static Teal(){return new ee(0,1,1)}static Random(){return new ee(Math.random(),Math.random(),Math.random())}}ee._BlackReadOnly=ee.Black(),Object.defineProperties(ee.prototype,{dimension:{value:[3]},rank:{value:1}});class te{constructor(e=0,t=0,i=0,n=1){this.r=e,this.g=t,this.b=i,this.a=n}asArray(){return[this.r,this.g,this.b,this.a]}toArray(e,t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e[t+3]=this.a,this}fromArray(e,t=0){return this.r=e[t],this.g=e[t+1],this.b=e[t+2],this.a=e[t+3],this}equals(e){return e&&this.r===e.r&&this.g===e.g&&this.b===e.b&&this.a===e.a}add(e){return new te(this.r+e.r,this.g+e.g,this.b+e.b,this.a+e.a)}addToRef(e,t){return t.r=this.r+e.r,t.g=this.g+e.g,t.b=this.b+e.b,t.a=this.a+e.a,t}addInPlace(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this.a+=e.a,this}addInPlaceFromFloats(e,t,i,n){return this.r+=e,this.g+=t,this.b+=i,this.a+=n,this}subtract(e){return new te(this.r-e.r,this.g-e.g,this.b-e.b,this.a-e.a)}subtractToRef(e,t){return t.r=this.r-e.r,t.g=this.g-e.g,t.b=this.b-e.b,t.a=this.a-e.a,t}subtractInPlace(e){return this.r-=e.r,this.g-=e.g,this.b-=e.b,this.a-=e.a,this}subtractFromFloats(e,t,i,n){return new te(this.r-e,this.g-t,this.b-i,this.a-n)}subtractFromFloatsToRef(e,t,i,n,r){return r.r=this.r-e,r.g=this.g-t,r.b=this.b-i,r.a=this.a-n,r}scale(e){return new te(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=P(this.r,e,t),i.g=P(this.g,e,t),i.b=P(this.b,e,t),i.a=P(this.a,e,t),i}multiply(e){return new te(this.r*e.r,this.g*e.g,this.b*e.b,this.a*e.a)}multiplyToRef(e,t){return t.r=this.r*e.r,t.g=this.g*e.g,t.b=this.b*e.b,t.a=this.a*e.a,t}multiplyInPlace(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this.a*=e.a,this}multiplyByFloats(e,t,i,n){return new te(this.r*e,this.g*t,this.b*i,this.a*n)}divide(e){throw new ReferenceError("Can not divide a color")}divideToRef(e,t){throw new ReferenceError("Can not divide a color")}divideInPlace(e){throw new ReferenceError("Can not divide a color")}minimizeInPlace(e){return this.r=Math.min(this.r,e.r),this.g=Math.min(this.g,e.g),this.b=Math.min(this.b,e.b),this.a=Math.min(this.a,e.a),this}maximizeInPlace(e){return this.r=Math.max(this.r,e.r),this.g=Math.max(this.g,e.g),this.b=Math.max(this.b,e.b),this.a=Math.max(this.a,e.a),this}minimizeInPlaceFromFloats(e,t,i,n){return this.r=Math.min(e,this.r),this.g=Math.min(t,this.g),this.b=Math.min(i,this.b),this.a=Math.min(n,this.a),this}maximizeInPlaceFromFloats(e,t,i,n){return this.r=Math.max(e,this.r),this.g=Math.max(t,this.g),this.b=Math.max(i,this.b),this.a=Math.max(n,this.a),this}floorToRef(e){throw new ReferenceError("Can not floor a color")}floor(){throw new ReferenceError("Can not floor a color")}fractToRef(e){throw new ReferenceError("Can not fract a color")}fract(){throw new ReferenceError("Can not fract a color")}negate(){throw new ReferenceError("Can not negate a color")}negateInPlace(){throw new ReferenceError("Can not negate a color")}negateToRef(e){throw new ReferenceError("Can not negate a color")}equalsWithEpsilon(e,t=A){return j.WithinEpsilon(this.r,e.r,t)&&j.WithinEpsilon(this.g,e.g,t)&&j.WithinEpsilon(this.b,e.b,t)&&j.WithinEpsilon(this.a,e.a,t)}equalsToFloats(e,t,i,n){return this.r===e&&this.g===t&&this.b===i&&this.a===n}toString(){return"{R: "+this.r+" G:"+this.g+" B:"+this.b+" A:"+this.a+"}"}getClassName(){return"Color4"}getHashCode(){let e=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 te).copyFrom(this)}copyFrom(e){return this.r=e.r,this.g=e.g,this.b=e.b,this.a=e.a,this}copyFromFloats(e,t,i,n){return this.r=e,this.g=t,this.b=i,this.a=n,this}set(e,t,i,n){return this.copyFromFloats(e,t,i,n)}setAll(e){return this.r=this.g=this.b=this.a=e,this}toHexString(e=!1){const t=Math.round(255*this.r),i=Math.round(255*this.g),n=Math.round(255*this.b);if(e)return"#"+F(t)+F(i)+F(n);const r=Math.round(255*this.a);return"#"+F(t)+F(i)+F(n)+F(r)}toLinearSpace(e=!1){const t=new te;return this.toLinearSpaceToRef(t,e),t}toLinearSpaceToRef(e,t=!1){return t?(e.r=Z(this.r),e.g=Z(this.g),e.b=Z(this.b)):(e.r=Q(this.r),e.g=Q(this.g),e.b=Q(this.b)),e.a=this.a,this}toGammaSpace(e=!1){const t=new te;return this.toGammaSpaceToRef(t,e),t}toGammaSpaceToRef(e,t=!1){return t?(e.r=$(this.r),e.g=$(this.g),e.b=$(this.b)):(e.r=J(this.r),e.g=J(this.g),e.b=J(this.b)),e.a=this.a,this}static FromHexString(e){if("#"!==e.substring(0,1)||9!==e.length&&7!==e.length)return new te(0,0,0,0);const t=parseInt(e.substring(1,3),16),i=parseInt(e.substring(3,5),16),n=parseInt(e.substring(5,7),16),r=9===e.length?parseInt(e.substring(7,9),16):255;return te.FromInts(t,i,n,r)}static Lerp(e,t,i){return te.LerpToRef(e,t,i,new te)}static LerpToRef(e,t,i,n){return n.r=e.r+(t.r-e.r)*i,n.g=e.g+(t.g-e.g)*i,n.b=e.b+(t.b-e.b)*i,n.a=e.a+(t.a-e.a)*i,n}static Hermite(e,t,i,n,r){const s=r*r,a=r*s,o=2*a-3*s+1,l=-2*a+3*s,c=a-2*s+r,h=a-s,d=e.r*o+i.r*l+t.r*c+n.r*h,u=e.g*o+i.g*l+t.g*c+n.g*h,f=e.b*o+i.b*l+t.b*c+n.b*h,_=e.a*o+i.a*l+t.a*c+n.a*h;return new te(d,u,f,_)}static Hermite1stDerivative(e,t,i,n,r){const s=new te;return this.Hermite1stDerivativeToRef(e,t,i,n,r,s),s}static Hermite1stDerivativeToRef(e,t,i,n,r,s){const a=r*r;s.r=6*(a-r)*e.r+(3*a-4*r+1)*t.r+6*(-a+r)*i.r+(3*a-2*r)*n.r,s.g=6*(a-r)*e.g+(3*a-4*r+1)*t.g+6*(-a+r)*i.g+(3*a-2*r)*n.g,s.b=6*(a-r)*e.b+(3*a-4*r+1)*t.b+6*(-a+r)*i.b+(3*a-2*r)*n.b,s.a=6*(a-r)*e.a+(3*a-4*r+1)*t.a+6*(-a+r)*i.a+(3*a-2*r)*n.a}static FromColor3(e,t=1){return new te(e.r,e.g,e.b,t)}static FromArray(e,t=0){return new te(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t=0,i){i.r=e[t],i.g=e[t+1],i.b=e[t+2],i.a=e[t+3]}static FromInts(e,t,i,n){return new te(e/255,t/255,i/255,n/255)}static CheckColors4(e,t){if(e.length===3*t){const t=[];for(let i=0;i<e.length;i+=3){const n=i/3*4;t[n]=e[i],t[n+1]=e[i+1],t[n+2]=e[i+2],t[n+3]=1}return t}return e}}Object.defineProperties(te.prototype,{dimension:{value:[4]},rank:{value:1}});class ie{}ie.Color3=v(3,ee.Black),ie.Color4=v(3,(()=>new te(0,0,0,0))),M("BABYLON.Color3",ee),M("BABYLON.Color4",te);const ne=function(e,t,i,r={}){const s=e();q&&q.HasTags(t)&&q.AddTagsTo(s,q.GetTags(t,!0));const a=n(s),o={};for(const e in a){const n=a[e],l=t[e],c=n.type;if(null!=l&&("uniqueId"!==e||re.AllowLoadingUniqueId))switch(c){case 0:case 6:case 11:s[e]=l;break;case 1:r.cloneTexturesOnlyOnce&&o[l.uniqueId]?s[e]=o[l.uniqueId]:(s[e]=i||l.isRenderTarget?l:l.clone(),o[l.uniqueId]=s[e]);break;case 2:case 3:case 4:case 5:case 7:case 10:case 12:s[e]=i?l:l.clone()}}return s};class re{static AppendSerializedAnimations(e,t){if(e.animations){t.animations=[];for(let i=0;i<e.animations.length;i++){const n=e.animations[i];t.animations.push(n.serialize())}}}static Serialize(e,t){t||(t={}),q&&(t.tags=q.GetTags(e));const i=n(e);for(const n in i){const r=i[n],s=r.sourceName||n,a=r.type,o=e[n];if(null!=o&&("uniqueId"!==n||re.AllowLoadingUniqueId))switch(a){case 0:t[s]=o;break;case 1:case 3:case 7:case 9:t[s]=o.serialize();break;case 2:case 4:case 5:case 8:case 10:case 12:t[s]=o.asArray();break;case 6:case 11:t[s]=o.id}}return t}static ParseProperties(e,t,i,r){r||(r="");const s=n(t);for(const n in s){const a=s[n],o=e[a.sourceName||n],l=a.type;if(null!=o&&("uniqueId"!==n||re.AllowLoadingUniqueId)){const e=t;switch(l){case 0:e[n]=o;break;case 1:i&&(e[n]=re._TextureParser(o,i,r));break;case 2:e[n]=ee.FromArray(o);break;case 3:e[n]=re._FresnelParametersParser(o);break;case 4:e[n]=U.FromArray(o);break;case 5:e[n]=B.FromArray(o);break;case 6:i&&(e[n]=i.getLastMeshById(o));break;case 7:e[n]=re._ColorCurvesParser(o);break;case 8:e[n]=te.FromArray(o);break;case 9:e[n]=re._ImageProcessingConfigurationParser(o);break;case 10:e[n]=V.FromArray(o);break;case 11:i&&(e[n]=i.getCameraById(o));break;case 12:e[n]=k.FromArray(o)}}}}static Parse(e,t,i,n=null){const r=e();return q&&q.AddTagsTo(r,t.tags),re.ParseProperties(t,r,i,n),r}static Clone(e,t,i={}){return ne(e,t,!1,i)}static Instanciate(e,t){return ne(e,t,!0)}}re.AllowLoadingUniqueId=!1,re._ImageProcessingConfigurationParser=e=>{throw Y("ImageProcessingConfiguration")},re._FresnelParametersParser=e=>{throw Y("FresnelParameters")},re._ColorCurvesParser=e=>{throw Y("ColorCurves")},re._TextureParser=(e,t,i)=>{throw Y("Texture")};class se{constructor(){this._doNotSerialize=!1,this._isDisposed=!1,this._sceneRootNodesIndex=-1,this._isEnabled=!0,this._isParentEnabled=!0,this._isReady=!0,this._onEnabledStateChangedObservable=new g,this._onClonedObservable=new g}}class ae{static AddNodeConstructor(e,t){this._NodeConstructors[e]=t}static Construct(e,t,i,n){const r=this._NodeConstructors[e];return r?r(t,i,n):null}set accessibilityTag(e){this._accessibilityTag=e,this.onAccessibilityTagChangedObservable.notifyObservers(e)}get accessibilityTag(){return this._accessibilityTag}get doNotSerialize(){return!!this._nodeDataStorage._doNotSerialize||!!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 se,this.state="",this.metadata=null,this.reservedDataStore=null,this._accessibilityTag=null,this.onAccessibilityTagChangedObservable=new g,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=k.Identity(),this._worldMatrixDeterminant=0,this._worldMatrixDeterminantIsDirty=!0,this._animationPropertiesOverride=null,this._isNode=!0,this.onDisposeObservable=new g,this._onDisposeObserver=null,this._behaviors=new Array,this.name=e,this.id=e,this._scene=t||y.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 n=0;n<this._children.length;n++){const r=this._children[n];i&&!i(r)||e.push(r),t||r._getDescendants(e,!1,i)}}getDescendants(e,t){const i=[];return this._getDescendants(i,e,t),i}getChildMeshes(e,t){const i=[];return this._getDescendants(i,e,(e=>(!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;t<this.animations.length;t++){const i=this.animations[t];if(i.name===e)return i}return null}createAnimationRange(e,t,i){if(!this._ranges[e]){this._ranges[e]=ae._AnimationRangeFactory(e,t,i);for(let n=0,r=this.animations.length;n<r;n++)this.animations[n]&&this.animations[n].createRange(e,t,i)}}deleteAnimationRange(e,t=!0){for(let i=0,n=this.animations.length;i<n;i++)this.animations[i]&&this.animations[i].deleteRange(e,t);this._ranges[e]=null}getAnimationRange(e){return this._ranges[e]||null}clone(e,t,i){const n=re.Clone((()=>new ae(e,this.getScene())),this);if(t&&(n.parent=t),!i){const t=this.getDescendants(!0);for(let i=0;i<t.length;i++){const r=t[i];r.clone(e+"."+r.name,n)}}return n}getAnimationRanges(){const e=[];let t;for(t in this._ranges)e.push(this._ranges[t]);return e}beginAnimation(e,t,i,n){const r=this.getAnimationRange(e);return r?this._scene.beginAnimation(this,r.from,r.to,t,i,n):null}serializeAnimationRanges(){const e=[];for(const t in this._ranges){const i=this._ranges[t];if(!i)continue;const n={};n.name=t,n.from=i.from,n.to=i.to,e.push(n)}return e}computeWorldMatrix(e){return this._worldMatrix||(this._worldMatrix=k.Identity()),this._worldMatrix}dispose(e,t=!1){if(this._nodeDataStorage._isDisposed=!0,!e){const i=this.getDescendants(!0);for(const n of i)n.dispose(e,t)}this.parent?this.parent=null:this._removeFromSceneRootNodes(),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onEnabledStateChangedObservable.clear(),this.onClonedObservable.clear();for(const e of this._behaviors)e.detach();this._behaviors.length=0,this.metadata=null}static ParseAnimationRanges(e,t,i){if(t.ranges)for(let i=0;i<t.ranges.length;i++){const n=t.ranges[i];e.createAnimationRange(n.name,n.from,n.to)}}getHierarchyBoundingVectors(e=!0,t=null){let i,n;this.getScene().incrementRenderId(),this.computeWorldMatrix(!0);const r=this;if(r.getBoundingInfo&&r.subMeshes){const e=r.getBoundingInfo();i=e.boundingBox.minimumWorld.clone(),n=e.boundingBox.maximumWorld.clone()}else i=new B(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),n=new B(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);if(e){const e=this.getDescendants(!1);for(const r of e){const e=r;if(e.computeWorldMatrix(!0),t&&!t(e))continue;if(!e.getBoundingInfo||0===e.getTotalVertices())continue;const s=e.getBoundingInfo().boundingBox,a=s.minimumWorld,o=s.maximumWorld;B.CheckExtends(a,i,n),B.CheckExtends(o,i,n)}}return{min:i,max:n}}}function oe(){return"undefined"!=typeof window}function le(){return"undefined"!=typeof navigator}function ce(){return"undefined"!=typeof document}function he(e){let t="",i=e.firstChild;for(;i;)3===i.nodeType&&(t+=i.textContent),i=i.nextSibling;return t}ae._AnimationRangeFactory=(e,t,i)=>{throw Y("AnimationRange")},ae._NodeConstructors={},e([a()],ae.prototype,"name",void 0),e([a()],ae.prototype,"id",void 0),e([a()],ae.prototype,"uniqueId",void 0),e([a()],ae.prototype,"state",void 0),e([a()],ae.prototype,"metadata",void 0);class de{static _CheckLimit(e,t){let i=de._LogLimitOutputs[e];return i?i.current++:(i={limit:t,current:1},de._LogLimitOutputs[e]=i),i.current<=i.limit}static _GenerateLimitMessage(e,t=1){const i=de._LogLimitOutputs[e];if(!i||!de.MessageLimitReached)return;const n=this._Levels[t];i.current===i.limit&&de[n.name](de.MessageLimitReached.replace(/%LIMIT%/g,""+i.limit).replace(/%TYPE%/g,n.name??""))}static _AddLogEntry(e){de._LogCache=e+de._LogCache,de.OnNewCacheEntry&&de.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 n=Array.isArray(t)?t[0]:t;if(void 0!==i&&!de._CheckLimit(n,i))return;const r=de._FormatMessage(n),s=this._Levels[e],a=Array.isArray(t)?t.slice(1):[];s.logFunc&&s.logFunc("BJS - "+r,...a);const o=`<div style='color:${s.color}'>${r}</div><br>`;de._AddLogEntry(o),de._GenerateLimitMessage(n,e)}static get LogCache(){return de._LogCache}static ClearLogCache(){de._LogCache="",de._LogLimitOutputs={},de.errorsCount=0}static set LogLevels(e){de.Log=de._LogDisabled,de.Warn=de._LogDisabled,de.Error=de._LogDisabled,[de.MessageLogLevel,de.WarningLogLevel,de.ErrorLogLevel].forEach((t=>{if((e&t)===t){const e=this._Levels[t];de[e.name]=de._LogEnabled.bind(de,t)}}))}}de.NoneLogLevel=0,de.MessageLogLevel=1,de.WarningLogLevel=2,de.ErrorLogLevel=4,de.AllLogLevel=7,de.MessageLimitReached="Too many %TYPE%s (%LIMIT%), no more %TYPE%s will be reported for this message.",de._LogCache="",de._LogLimitOutputs={},de._Levels=[{},{color:"white",logFunc:console.log,name:"Log"},{color:"orange",logFunc:console.warn,name:"Warn"},{},{color:"red",logFunc:console.error,name:"Error"}],de.errorsCount=0,de.Log=de._LogEnabled.bind(de,de.MessageLogLevel),de.Warn=de._LogEnabled.bind(de,de.WarningLogLevel),de.Error=de._LogEnabled.bind(de,de.ErrorLogLevel);const ue=(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 fe{static DeepCopy(e,t,i,n,r=!1){const s=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 a of s){if("_"===a[0]&&(!n||-1===n.indexOf(a)))continue;if(a.endsWith("Observable"))continue;if(i&&-1!==i.indexOf(a))continue;const s=e[a],o=typeof s;if("function"!==o)try{if("object"===o)if(s instanceof Uint8Array)t[a]=Uint8Array.from(s);else if(s instanceof Array){if(t[a]=[],s.length>0)if("object"==typeof s[0])for(let e=0;e<s.length;e++){const i=ue(s[e],t,r);-1===t[a].indexOf(i)&&t[a].push(i)}else t[a]=s.slice(0)}else t[a]=ue(s,t,r);else t[a]=s}catch(e){de.Warn(e.message)}}}}class _e{static get Now(){return oe()&&window.performance&&window.performance.now?window.performance.now():Date.now()}}class me{constructor(){this._xhr="undefined"!=typeof _native&&_native.XMLHttpRequest?new _native.XMLHttpRequest:new XMLHttpRequest,this._requestURL=""}static get IsCustomRequestAvailable(){return Object.keys(me.CustomRequestHeaders).length>0||me.CustomRequestModifiers.length>0}_injectCustomRequestHeaders(){if(!this._shouldSkipRequestModifications(this._requestURL))for(const e in me.CustomRequestHeaders){const t=me.CustomRequestHeaders[e];t&&this._xhr.setRequestHeader(e,t)}}_shouldSkipRequestModifications(e){return me.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){me.CustomRequestHeaders&&this._injectCustomRequestHeaders(),this._xhr.send(e)}open(e,t){for(const e of me.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)}}me.CustomRequestHeaders={},me.CustomRequestModifiers=new Array,me.SkipRequestModificationForBabylonCDN=!0;class pe{}pe.FilesToLoad={};class ge extends Error{}ge._setPrototypeOf=Object.setPrototypeOf||((e,t)=>(e.__proto__=t,e));const Ee={MeshInvalidPositionsError:0,UnsupportedTextureError:1e3,GLTFLoaderUnexpectedMagicError:2e3,SceneLoaderError:3e3,LoadFileError:4e3,RequestFileError:4001,ReadFileError:4002};class Te extends ge{constructor(e,t,i){super(e),this.errorCode=t,this.innerError=i,this.name="RuntimeError",ge._setPrototypeOf(this,Te.prototype)}}const Ae=e=>{const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";let i,n,r,s,a,o,l,c="",h=0;const d=ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e);for(;h<d.length;)i=d[h++],n=h<d.length?d[h++]:Number.NaN,r=h<d.length?d[h++]:Number.NaN,s=i>>2,a=(3&i)<<4|n>>4,o=(15&n)<<2|r>>6,l=63&r,isNaN(n)?o=l=64:isNaN(r)&&(l=64),c+=t.charAt(s)+t.charAt(a)+t.charAt(o)+t.charAt(l);return c},ve=e=>atob(e);class Re{constructor(){this.children=[]}isValid(e){return!0}process(e,t){let i="";if(this.line){let n=this.line;const r=t.processor;if(r){r.lineProcessor&&(n=r.lineProcessor(n,t.isFragment,t.processingContext));const i=t.processor?.attributeKeywordName??"attribute",s=t.isFragment&&t.processor?.varyingFragmentKeywordName?t.processor?.varyingFragmentKeywordName:!t.isFragment&&t.processor?.varyingVertexKeywordName?t.processor?.varyingVertexKeywordName:"varying";if(!t.isFragment&&r.attributeProcessor&&this.line.startsWith(i))n=r.attributeProcessor(this.line,e,t.processingContext);else if(r.varyingProcessor&&(r.varyingCheck?.(this.line,t.isFragment)||!r.varyingCheck&&this.line.startsWith(s)))n=r.varyingProcessor(this.line,t.isFragment,e,t.processingContext);else if(r.uniformProcessor&&r.uniformRegexp&&r.uniformRegexp.test(this.line))t.lookForClosingBracketForUniformBuffer||(n=r.uniformProcessor(this.line,t.isFragment,e,t.processingContext));else if(r.uniformBufferProcessor&&r.uniformBufferRegexp&&r.uniformBufferRegexp.test(this.line))t.lookForClosingBracketForUniformBuffer||(n=r.uniformBufferProcessor(this.line,t.isFragment,t.processingContext),t.lookForClosingBracketForUniformBuffer=!0);else if(r.textureProcessor&&r.textureRegexp&&r.textureRegexp.test(this.line))n=r.textureProcessor(this.line,t.isFragment,e,t.processingContext);else if((r.uniformProcessor||r.uniformBufferProcessor)&&this.line.startsWith("uniform")&&!t.lookForClosingBracketForUniformBuffer){/uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/.test(this.line)?r.uniformProcessor&&(n=r.uniformProcessor(this.line,t.isFragment,e,t.processingContext)):r.uniformBufferProcessor&&(n=r.uniformBufferProcessor(this.line,t.isFragment,t.processingContext),t.lookForClosingBracketForUniformBuffer=!0)}t.lookForClosingBracketForUniformBuffer&&-1!==this.line.indexOf("}")&&(t.lookForClosingBracketForUniformBuffer=!1,r.endOfUniformBufferProcessor&&(n=r.endOfUniformBufferProcessor(this.line,t.isFragment,t.processingContext)))}i+=n+"\n"}return this.children.forEach((n=>{i+=n.process(e,t)})),this.additionalDefineKey&&(e[this.additionalDefineKey]=this.additionalDefineValue||"true"),i}}class Se{constructor(){this._lines=[]}get currentLine(){return this._lines[this.lineIndex]}get canRead(){return this.lineIndex<this._lines.length-1}set lines(e){this._lines.length=0;for(const t of e){if(!t||"\r"===t)continue;if("#"===t[0]){this._lines.push(t);continue}const e=t.trim();if(!e)continue;if(e.startsWith("//")){this._lines.push(t);continue}const i=e.indexOf(";");if(-1===i)this._lines.push(e);else if(i===e.length-1)e.length>1&&this._lines.push(e);else{const e=t.split(";");for(let t=0;t<e.length;t++){let i=e[t];i&&(i=i.trim(),i&&this._lines.push(i+(t!==e.length-1?";":"")))}}}}}class Ie extends Re{process(e,t){for(let i=0;i<this.children.length;i++){const n=this.children[i];if(n.isValid(e))return n.process(e,t)}return""}}class Ce extends Re{isValid(e){return this.testExpression.isTrue(e)}}class Me{isTrue(e){return!0}static postfixToInfix(e){const t=[];for(const i of e)if(void 0===Me._OperatorPriority[i])t.push(i);else{const e=t[t.length-1],n=t[t.length-2];t.length-=2,t.push(`(${n}${i}${e})`)}return t[t.length-1]}static infixToPostfix(e){const t=Me._InfixToPostfixCache.get(e);if(t)return t.accessTime=Date.now(),t.result;if(!(e.includes("&&")||e.includes("||")||e.includes(")")||e.includes("(")))return[e];const i=[];let n=-1;const r=()=>{c=c.trim(),""!==c&&(i.push(c),c="")},s=e=>{n<Me._Stack.length-1&&(Me._Stack[++n]=e)},a=()=>Me._Stack[n],o=()=>-1===n?"!!INVALID EXPRESSION!!":Me._Stack[n--];let l=0,c="";for(;l<e.length;){const t=e.charAt(l),h=l<e.length-1?e.substr(l,2):"";if("("===t)c="",s(t);else if(")"===t){for(r();-1!==n&&"("!==a();)i.push(o());o()}else if(Me._OperatorPriority[h]>1){for(r();-1!==n&&Me._OperatorPriority[a()]>=Me._OperatorPriority[h];)i.push(o());s(h),l++}else c+=t;l++}for(r();-1!==n;)"("===a()?o():i.push(o());return Me._InfixToPostfixCache.size>=Me.InfixToPostfixCacheLimitSize&&Me.ClearCache(),Me._InfixToPostfixCache.set(e,{result:i,accessTime:Date.now()}),i}static ClearCache(){const e=Array.from(Me._InfixToPostfixCache.entries()).sort(((e,t)=>e[1].accessTime-t[1].accessTime));for(let t=0;t<Me.InfixToPostfixCacheCleanupSize;t++)Me._InfixToPostfixCache.delete(e[t][0])}}Me.InfixToPostfixCacheLimitSize=5e4,Me.InfixToPostfixCacheCleanupSize=25e3,Me._InfixToPostfixCache=new Map,Me._OperatorPriority={")":0,"(":1,"||":2,"&&":3},Me._Stack=["","","","","","","","","","","","","","","","","","","",""];class xe extends Me{constructor(e,t=!1){super(),this.define=e,this.not=t}isTrue(e){let t=void 0!==e[this.define];return this.not&&(t=!t),t}}class be extends Me{isTrue(e){return this.leftOperand.isTrue(e)||this.rightOperand.isTrue(e)}}class ye extends Me{isTrue(e){return this.leftOperand.isTrue(e)&&this.rightOperand.isTrue(e)}}class Oe extends Me{constructor(e,t,i){super(),this.define=e,this.operand=t,this.testValue=i}isTrue(e){let t=e[this.define];void 0===t&&(t=this.define);let i=!1;const n=parseInt(t),r=parseInt(this.testValue);switch(this.operand){case">":i=n>r;break;case"<":i=n<r;break;case"<=":i=n<=r;break;case">=":i=n>=r;break;case"==":i=n===r;break;case"!=":i=n!==r}return i}}const De={};function Ne(e,t,i=""){return i+(t?t+"\n":"")+e}function Pe(e,t,i,n,r,s,a){const o=a||De.loadFile;if(o){return o(e,t,i,n,r,s)}throw Y("FileTools")}function Le(e,t,i,n){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(n?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"),n&&(e&&(e+="\n"),e+="#define USE_EXACT_SRGB_CONVERSIONS"),e}}const Fe=/defined\s*?\((.+?)\)/g,we=/defined\s*?\[(.+?)\]/g,Ue=/#include\s?<(.+)>(\((.*)\))*(\[(.*)\])*/g,Be=/__decl__/,Ge=/light\{X\}.(\w*)/g,Ve=/\{X\}/g,ke=[],Xe=/(#ifdef)|(#else)|(#elif)|(#endif)|(#ifndef)|(#if)/;function He(e,t,i,n){t.processor?.preProcessShaderCode&&(e=t.processor.preProcessShaderCode(e,t.isFragment)),qe(e,t,(e=>{t.processCodeAfterIncludes&&(e=t.processCodeAfterIncludes(t.isFragment?"fragment":"vertex",e,t.defines));const r=function(e,t,i){let n=function(e,t){if(t.processor?.noPrecision)return e;const i=t.shouldUseHighPrecisionShader;-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"));return e}(e,t);if(!t.processor)return n;if(0===t.processor.shaderLanguage&&-1!==n.indexOf("#version 3")&&(n=n.replace("#version 300 es",""),!t.processor.parseGLES3))return n;const r=t.defines,s=function(e,t){const i=e.defines,n={};for(const e of i){const t=e.replace("#define","").replace(";","").trim().split(" ");n[t[0]]=t.length>1?t[1]:""}0===e.processor?.shaderLanguage&&(n.GL_ES="true");return n.__VERSION__=e.version,n[e.platformName]="true",Le(n,t?.isNDCHalfZRange,t?.useReverseDepthBuffer,t?.useExactSrgbConversions),n}(t,i);t.processor.preProcessor&&(n=t.processor.preProcessor(n,r,s,t.isFragment,t.processingContext));n=function(e,t,i){const n=new Re,r=new Se;return r.lineIndex=-1,r.lines=e.split("\n"),Ke(r,n),n.process(t,i)}(n,s,t),t.processor.postProcessor&&(n=t.processor.postProcessor(n,r,t.isFragment,t.processingContext,i?{drawBuffersExtensionDisabled:!i.getCaps().drawBuffersExtension}:{}));i?._features.needShaderCodeInlining&&(n=i.inlineShaderCode(n));return n}(e,t,n);i(r,e)}))}function We(e){const t=/defined\((.+)\)/.exec(e);if(t&&t.length)return new xe(t[1].trim(),"!"===e[0]);const i=["==","!=",">=","<=","<",">"];let n="",r=0;for(n of i)if(r=e.indexOf(n),r>-1)break;if(-1===r)return new xe(e);const s=e.substring(0,r).trim(),a=e.substring(r+n.length).trim();return new Oe(s,n,a)}function ze(e,t){const i=new Ce,n=e.substring(0,t);let r=e.substring(t);return r=r.substring(0,(r.indexOf("//")+1||r.length+1)-1).trim(),i.testExpression="#ifdef"===n?new xe(r):"#ifndef"===n?new xe(r,!0):function(e){e=e.replace(Fe,"defined[$1]");const t=Me.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],n=i[i.length-2];i.length-=2;const r="&&"==e?new ye:new be;"string"==typeof t&&(t=t.replace(we,"defined($1)")),"string"==typeof n&&(n=n.replace(we,"defined($1)")),r.leftOperand="string"==typeof n?We(n):n,r.rightOperand="string"==typeof t?We(t):t,i.push(r)}let n=i[i.length-1];return"string"==typeof n&&(n=n.replace(we,"defined($1)")),"string"==typeof n?We(n):n}(r),i}function Ye(e,t,i){let n=e.currentLine;for(;Ke(e,i);){n=e.currentLine;const r=n.substring(0,5).toLowerCase();if("#else"===r){const i=new Re;return t.children.push(i),void Ke(e,i)}if("#elif"===r){const e=ze(n,5);t.children.push(e),i=e}}}function Ke(e,t){for(;e.canRead;){e.lineIndex++;const i=e.currentLine;if(i.indexOf("#")>=0){const n=Xe.exec(i);if(n&&n.length){switch(n[0]){case"#ifdef":{const n=new Ie;t.children.push(n);const r=ze(i,6);n.children.push(r),Ye(e,n,r);break}case"#else":case"#elif":return!0;case"#endif":return!1;case"#ifndef":{const n=new Ie;t.children.push(n);const r=ze(i,7);n.children.push(r),Ye(e,n,r);break}case"#if":{const n=new Ie,r=ze(i,3);t.children.push(n),n.children.push(r),Ye(e,n,r);break}}continue}}const n=new Re;if(n.line=i,t.children.push(n),"#"===i[0]&&"d"===i[1]){const e=i.replace(";","").split(" ");n.additionalDefineKey=e[1],3===e.length&&(n.additionalDefineValue=e[2])}}return!1}function qe(e,t,i){let n;for(ke.length=0;null!==(n=Ue.exec(e));)ke.push(n);let r=String(e),s=[e],a=!1;for(const e of ke){let n=e[1];if(-1!==n.indexOf("__decl__")&&(n=n.replace(Be,""),t.supportsUniformBuffers&&(n=n.replace("Vertex","Ubo").replace("Fragment","Ubo")),n+="Declaration"),!t.includesShadersStore[n]){const e=t.shadersRepository+"ShadersInclude/"+n+".fx";return void je.loadFile(e,(e=>{t.includesShadersStore[n]=e,qe(s.join(""),t,i)}))}{let i=t.includesShadersStore[n];if(e[2]){const t=e[3].split(",");for(let e=0;e<t.length;e+=2){const n=new RegExp(t[e],"g"),r=t[e+1];i=i.replace(n,r)}}if(e[4]){const n=e[5];if(-1!==n.indexOf("..")){const e=n.split(".."),r=parseInt(e[0]);let s=parseInt(e[1]),a=i.slice(0);i="",isNaN(s)&&(s=t.indexParameters[e[1]]);for(let e=r;e<s;e++)t.supportsUniformBuffers||(a=a.replace(Ge,((e,t)=>t+"{X}"))),i+=a.replace(Ve,e.toString())+"\n"}else t.supportsUniformBuffers||(i=i.replace(Ge,((e,t)=>t+"{X}"))),i=i.replace(Ve,n)}const r=[];for(const t of s){const n=t.split(e[0]);for(let e=0;e<n.length-1;e++)r.push(n[e]),r.push(i);r.push(n[n.length-1])}s=r,a=a||i.indexOf("#include<")>=0||i.indexOf("#include <")>=0}}ke.length=0,r=s.join(""),a?qe(r.toString(),t,i):i(r)}const je={loadFile:(e,t,i,n,r,s)=>{throw Y("FileTools")}};class Qe{static SetImmediate(e){oe()&&window.setImmediate?window.setImmediate(e):setTimeout(e,1)}}class Ze{}Ze.AUTOSAMPLERSUFFIX="Sampler",Ze.DISABLEUA="#define DISABLE_UNIFORMITY_ANALYSIS",Ze.ALPHA_DISABLE=0,Ze.ALPHA_ADD=1,Ze.ALPHA_COMBINE=2,Ze.ALPHA_SUBTRACT=3,Ze.ALPHA_MULTIPLY=4,Ze.ALPHA_MAXIMIZED=5,Ze.ALPHA_ONEONE=6,Ze.ALPHA_PREMULTIPLIED=7,Ze.ALPHA_PREMULTIPLIED_PORTERDUFF=8,Ze.ALPHA_INTERPOLATE=9,Ze.ALPHA_SCREENMODE=10,Ze.ALPHA_ONEONE_ONEONE=11,Ze.ALPHA_ALPHATOCOLOR=12,Ze.ALPHA_REVERSEONEMINUS=13,Ze.ALPHA_SRC_DSTONEMINUSSRCALPHA=14,Ze.ALPHA_ONEONE_ONEZERO=15,Ze.ALPHA_EXCLUSION=16,Ze.ALPHA_LAYER_ACCUMULATE=17,Ze.ALPHA_EQUATION_ADD=0,Ze.ALPHA_EQUATION_SUBSTRACT=1,Ze.ALPHA_EQUATION_REVERSE_SUBTRACT=2,Ze.ALPHA_EQUATION_MAX=3,Ze.ALPHA_EQUATION_MIN=4,Ze.ALPHA_EQUATION_DARKEN=5,Ze.DELAYLOADSTATE_NONE=0,Ze.DELAYLOADSTATE_LOADED=1,Ze.DELAYLOADSTATE_LOADING=2,Ze.DELAYLOADSTATE_NOTLOADED=4,Ze.NEVER=512,Ze.ALWAYS=519,Ze.LESS=513,Ze.EQUAL=514,Ze.LEQUAL=515,Ze.GREATER=516,Ze.GEQUAL=518,Ze.NOTEQUAL=517,Ze.KEEP=7680,Ze.ZERO=0,Ze.REPLACE=7681,Ze.INCR=7682,Ze.DECR=7683,Ze.INVERT=5386,Ze.INCR_WRAP=34055,Ze.DECR_WRAP=34056,Ze.TEXTURE_CLAMP_ADDRESSMODE=0,Ze.TEXTURE_WRAP_ADDRESSMODE=1,Ze.TEXTURE_MIRROR_ADDRESSMODE=2,Ze.TEXTURE_CREATIONFLAG_STORAGE=1,Ze.TEXTUREFORMAT_ALPHA=0,Ze.TEXTUREFORMAT_LUMINANCE=1,Ze.TEXTUREFORMAT_LUMINANCE_ALPHA=2,Ze.TEXTUREFORMAT_RGB=4,Ze.TEXTUREFORMAT_RGBA=5,Ze.TEXTUREFORMAT_RED=6,Ze.TEXTUREFORMAT_R=6,Ze.TEXTUREFORMAT_RG=7,Ze.TEXTUREFORMAT_RED_INTEGER=8,Ze.TEXTUREFORMAT_R_INTEGER=8,Ze.TEXTUREFORMAT_RG_INTEGER=9,Ze.TEXTUREFORMAT_RGB_INTEGER=10,Ze.TEXTUREFORMAT_RGBA_INTEGER=11,Ze.TEXTUREFORMAT_BGRA=12,Ze.TEXTUREFORMAT_DEPTH24_STENCIL8=13,Ze.TEXTUREFORMAT_DEPTH32_FLOAT=14,Ze.TEXTUREFORMAT_DEPTH16=15,Ze.TEXTUREFORMAT_DEPTH24=16,Ze.TEXTUREFORMAT_DEPTH24UNORM_STENCIL8=17,Ze.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8=18,Ze.TEXTUREFORMAT_STENCIL8=19,Ze.TEXTUREFORMAT_UNDEFINED=4294967295,Ze.TEXTUREFORMAT_COMPRESSED_RGBA_BPTC_UNORM=36492,Ze.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_BPTC_UNORM=36493,Ze.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT=36495,Ze.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_SIGNED_FLOAT=36494,Ze.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT5=33779,Ze.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT=35919,Ze.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT3=33778,Ze.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT=35918,Ze.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT1=33777,Ze.TEXTUREFORMAT_COMPRESSED_RGB_S3TC_DXT1=33776,Ze.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT=35917,Ze.TEXTUREFORMAT_COMPRESSED_SRGB_S3TC_DXT1_EXT=35916,Ze.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_4x4=37808,Ze.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR=37840,Ze.TEXTUREFORMAT_COMPRESSED_RGB_ETC1_WEBGL=36196,Ze.TEXTUREFORMAT_COMPRESSED_RGB8_ETC2=37492,Ze.TEXTUREFORMAT_COMPRESSED_SRGB8_ETC2=37493,Ze.TEXTUREFORMAT_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2=37494,Ze.TEXTUREFORMAT_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2=37495,Ze.TEXTUREFORMAT_COMPRESSED_RGBA8_ETC2_EAC=37496,Ze.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC=37497,Ze.TEXTURETYPE_UNSIGNED_BYTE=0,Ze.TEXTURETYPE_UNSIGNED_INT=0,Ze.TEXTURETYPE_FLOAT=1,Ze.TEXTURETYPE_HALF_FLOAT=2,Ze.TEXTURETYPE_BYTE=3,Ze.TEXTURETYPE_SHORT=4,Ze.TEXTURETYPE_UNSIGNED_SHORT=5,Ze.TEXTURETYPE_INT=6,Ze.TEXTURETYPE_UNSIGNED_INTEGER=7,Ze.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=8,Ze.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=9,Ze.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=10,Ze.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=11,Ze.TEXTURETYPE_UNSIGNED_INT_24_8=12,Ze.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=13,Ze.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=14,Ze.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=15,Ze.TEXTURETYPE_UNDEFINED=16,Ze.TEXTURE_2D=3553,Ze.TEXTURE_2D_ARRAY=35866,Ze.TEXTURE_CUBE_MAP=34067,Ze.TEXTURE_CUBE_MAP_ARRAY=3735928559,Ze.TEXTURE_3D=32879,Ze.TEXTURE_NEAREST_SAMPLINGMODE=1,Ze.TEXTURE_NEAREST_NEAREST=1,Ze.TEXTURE_BILINEAR_SAMPLINGMODE=2,Ze.TEXTURE_LINEAR_LINEAR=2,Ze.TEXTURE_TRILINEAR_SAMPLINGMODE=3,Ze.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3,Ze.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4,Ze.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5,Ze.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6,Ze.TEXTURE_NEAREST_LINEAR=7,Ze.TEXTURE_NEAREST_NEAREST_MIPLINEAR=8,Ze.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9,Ze.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10,Ze.TEXTURE_LINEAR_LINEAR_MIPNEAREST=11,Ze.TEXTURE_LINEAR_NEAREST=12,Ze.TEXTURE_EXPLICIT_MODE=0,Ze.TEXTURE_SPHERICAL_MODE=1,Ze.TEXTURE_PLANAR_MODE=2,Ze.TEXTURE_CUBIC_MODE=3,Ze.TEXTURE_PROJECTION_MODE=4,Ze.TEXTURE_SKYBOX_MODE=5,Ze.TEXTURE_INVCUBIC_MODE=6,Ze.TEXTURE_EQUIRECTANGULAR_MODE=7,Ze.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8,Ze.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,Ze.TEXTURE_FILTERING_QUALITY_OFFLINE=4096,Ze.TEXTURE_FILTERING_QUALITY_HIGH=64,Ze.TEXTURE_FILTERING_QUALITY_MEDIUM=16,Ze.TEXTURE_FILTERING_QUALITY_LOW=8,Ze.SCALEMODE_FLOOR=1,Ze.SCALEMODE_NEAREST=2,Ze.SCALEMODE_CEILING=3,Ze.MATERIAL_TextureDirtyFlag=1,Ze.MATERIAL_LightDirtyFlag=2,Ze.MATERIAL_FresnelDirtyFlag=4,Ze.MATERIAL_AttributesDirtyFlag=8,Ze.MATERIAL_MiscDirtyFlag=16,Ze.MATERIAL_PrePassDirtyFlag=32,Ze.MATERIAL_AllDirtyFlag=63,Ze.MATERIAL_TriangleFillMode=0,Ze.MATERIAL_WireFrameFillMode=1,Ze.MATERIAL_PointFillMode=2,Ze.MATERIAL_PointListDrawMode=3,Ze.MATERIAL_LineListDrawMode=4,Ze.MATERIAL_LineLoopDrawMode=5,Ze.MATERIAL_LineStripDrawMode=6,Ze.MATERIAL_TriangleStripDrawMode=7,Ze.MATERIAL_TriangleFanDrawMode=8,Ze.MATERIAL_ClockWiseSideOrientation=0,Ze.MATERIAL_CounterClockWiseSideOrientation=1,Ze.ACTION_NothingTrigger=0,Ze.ACTION_OnPickTrigger=1,Ze.ACTION_OnLeftPickTrigger=2,Ze.ACTION_OnRightPickTrigger=3,Ze.ACTION_OnCenterPickTrigger=4,Ze.ACTION_OnPickDownTrigger=5,Ze.ACTION_OnDoublePickTrigger=6,Ze.ACTION_OnPickUpTrigger=7,Ze.ACTION_OnPickOutTrigger=16,Ze.ACTION_OnLongPressTrigger=8,Ze.ACTION_OnPointerOverTrigger=9,Ze.ACTION_OnPointerOutTrigger=10,Ze.ACTION_OnEveryFrameTrigger=11,Ze.ACTION_OnIntersectionEnterTrigger=12,Ze.ACTION_OnIntersectionExitTrigger=13,Ze.ACTION_OnKeyDownTrigger=14,Ze.ACTION_OnKeyUpTrigger=15,Ze.PARTICLES_BILLBOARDMODE_Y=2,Ze.PARTICLES_BILLBOARDMODE_ALL=7,Ze.PARTICLES_BILLBOARDMODE_STRETCHED=8,Ze.PARTICLES_BILLBOARDMODE_STRETCHED_LOCAL=9,Ze.MESHES_CULLINGSTRATEGY_STANDARD=0,Ze.MESHES_CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1,Ze.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2,Ze.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3,Ze.SCENELOADER_NO_LOGGING=0,Ze.SCENELOADER_MINIMAL_LOGGING=1,Ze.SCENELOADER_SUMMARY_LOGGING=2,Ze.SCENELOADER_DETAILED_LOGGING=3,Ze.PREPASS_IRRADIANCE_TEXTURE_TYPE=0,Ze.PREPASS_POSITION_TEXTURE_TYPE=1,Ze.PREPASS_VELOCITY_TEXTURE_TYPE=2,Ze.PREPASS_REFLECTIVITY_TEXTURE_TYPE=3,Ze.PREPASS_COLOR_TEXTURE_TYPE=4,Ze.PREPASS_DEPTH_TEXTURE_TYPE=5,Ze.PREPASS_NORMAL_TEXTURE_TYPE=6,Ze.PREPASS_ALBEDO_SQRT_TEXTURE_TYPE=7,Ze.BUFFER_CREATIONFLAG_READ=1,Ze.BUFFER_CREATIONFLAG_WRITE=2,Ze.BUFFER_CREATIONFLAG_READWRITE=3,Ze.BUFFER_CREATIONFLAG_UNIFORM=4,Ze.BUFFER_CREATIONFLAG_VERTEX=8,Ze.BUFFER_CREATIONFLAG_INDEX=16,Ze.BUFFER_CREATIONFLAG_STORAGE=32,Ze.BUFFER_CREATIONFLAG_INDIRECT=64,Ze.RENDERPASS_MAIN=0,Ze.INPUT_ALT_KEY=18,Ze.INPUT_CTRL_KEY=17,Ze.INPUT_META_KEY1=91,Ze.INPUT_META_KEY2=92,Ze.INPUT_META_KEY3=93,Ze.INPUT_SHIFT_KEY=16,Ze.SNAPSHOTRENDERING_STANDARD=0,Ze.SNAPSHOTRENDERING_FAST=1,Ze.PERSPECTIVE_CAMERA=0,Ze.ORTHOGRAPHIC_CAMERA=1,Ze.FOVMODE_VERTICAL_FIXED=0,Ze.FOVMODE_HORIZONTAL_FIXED=1,Ze.RIG_MODE_NONE=0,Ze.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10,Ze.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11,Ze.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12,Ze.RIG_MODE_STEREOSCOPIC_OVERUNDER=13,Ze.RIG_MODE_STEREOSCOPIC_INTERLACED=14,Ze.RIG_MODE_VR=20,Ze.RIG_MODE_CUSTOM=22,Ze.MAX_SUPPORTED_UV_SETS=6,Ze.GL_ALPHA_EQUATION_ADD=32774,Ze.GL_ALPHA_EQUATION_MIN=32775,Ze.GL_ALPHA_EQUATION_MAX=32776,Ze.GL_ALPHA_EQUATION_SUBTRACT=32778,Ze.GL_ALPHA_EQUATION_REVERSE_SUBTRACT=32779,Ze.GL_ALPHA_FUNCTION_SRC=768,Ze.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_COLOR=769,Ze.GL_ALPHA_FUNCTION_SRC_ALPHA=770,Ze.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_ALPHA=771,Ze.GL_ALPHA_FUNCTION_DST_ALPHA=772,Ze.GL_ALPHA_FUNCTION_ONE_MINUS_DST_ALPHA=773,Ze.GL_ALPHA_FUNCTION_DST_COLOR=774,Ze.GL_ALPHA_FUNCTION_ONE_MINUS_DST_COLOR=775,Ze.GL_ALPHA_FUNCTION_SRC_ALPHA_SATURATED=776,Ze.GL_ALPHA_FUNCTION_CONSTANT_COLOR=32769,Ze.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_COLOR=32770,Ze.GL_ALPHA_FUNCTION_CONSTANT_ALPHA=32771,Ze.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_ALPHA=32772,Ze.SnippetUrl="https://snippet.babylonjs.com",Ze.FOGMODE_NONE=0,Ze.FOGMODE_EXP=1,Ze.FOGMODE_EXP2=2,Ze.FOGMODE_LINEAR=3,Ze.BYTE=5120,Ze.UNSIGNED_BYTE=5121,Ze.SHORT=5122,Ze.UNSIGNED_SHORT=5123,Ze.INT=5124,Ze.UNSIGNED_INT=5125,Ze.FLOAT=5126,Ze.PositionKind="position",Ze.NormalKind="normal",Ze.TangentKind="tangent",Ze.UVKind="uv",Ze.UV2Kind="uv2",Ze.UV3Kind="uv3",Ze.UV4Kind="uv4",Ze.UV5Kind="uv5",Ze.UV6Kind="uv6",Ze.ColorKind="color",Ze.ColorInstanceKind="instanceColor",Ze.MatricesIndicesKind="matricesIndices",Ze.MatricesWeightsKind="matricesWeights",Ze.MatricesIndicesExtraKind="matricesIndicesExtra",Ze.MatricesWeightsExtraKind="matricesWeightsExtra";class Je{static GetShadersRepository(e=0){return 0===e?Je.ShadersRepository:Je.ShadersRepositoryWGSL}static GetShadersStore(e=0){return 0===e?Je.ShadersStore:Je.ShadersStoreWGSL}static GetIncludesShadersStore(e=0){return 0===e?Je.IncludesShadersStore:Je.IncludesShadersStoreWGSL}}Je.ShadersRepository="src/Shaders/",Je.ShadersStore={},Je.IncludesShadersStore={},Je.ShadersRepositoryWGSL="src/ShadersWGSL/",Je.ShadersStoreWGSL={},Je.IncludesShadersStoreWGSL={};class $e{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,n,r,s,a,o){const l=this.engine;if(l.supportsUniformBuffers)for(const i in t)e.bindUniformBlock(i,t[i]);let c;for(this.engine.getUniforms(this,i).forEach(((e,t)=>{n[i[t]]=e})),this._uniforms=n,c=0;c<r.length;c++){null==e.getUniform(r[c])&&(r.splice(c,1),c--)}r.forEach(((e,t)=>{s[e]=t}));for(const e of l.getAttributes(this,a))o.push(e)}dispose(){this._uniforms={},this._isDisposed=!0}_cacheMatrix(e,t){const i=this._valueCache[e],n=t.updateFlag;return(void 0===i||i!==n)&&(this._valueCache[e]=n,!0)}_cacheFloat2(e,t,i){let n=this._valueCache[e];if(!n||2!==n.length)return n=[t,i],this._valueCache[e]=n,!0;let r=!1;return n[0]!==t&&(n[0]=t,r=!0),n[1]!==i&&(n[1]=i,r=!0),r}_cacheFloat3(e,t,i,n){let r=this._valueCache[e];if(!r||3!==r.length)return r=[t,i,n],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),r[2]!==n&&(r[2]=n,s=!0),s}_cacheFloat4(e,t,i,n,r){let s=this._valueCache[e];if(!s||4!==s.length)return s=[t,i,n,r],this._valueCache[e]=s,!0;let a=!1;return s[0]!==t&&(s[0]=t,a=!0),s[1]!==i&&(s[1]=i,a=!0),s[2]!==n&&(s[2]=n,a=!0),s[3]!==r&&(s[3]=r,a=!0),a}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,n){this._cacheFloat3(e,t,i,n)&&(this.engine.setInt3(this._uniforms[e],t,i,n)||(this._valueCache[e]=null))}setInt4(e,t,i,n,r){this._cacheFloat4(e,t,i,n,r)&&(this.engine.setInt4(this._uniforms[e],t,i,n,r)||(this._valueCache[e]=null))}setIntArray(e,t){this._valueCache[e]=null,this.engine.setIntArray(this._uniforms[e],t)}setIntArray2(e,t){this._valueCache[e]=null,this.engine.setIntArray2(this._uniforms[e],t)}setIntArray3(e,t){this._valueCache[e]=null,this.engine.setIntArray3(this._uniforms[e],t)}setIntArray4(e,t){this._valueCache[e]=null,this.engine.setIntArray4(this._uniforms[e],t)}setUInt(e,t){const i=this._valueCache[e];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,n){this._cacheFloat3(e,t,i,n)&&(this.engine.setUInt3(this._uniforms[e],t,i,n)||(this._valueCache[e]=null))}setUInt4(e,t,i,n,r){this._cacheFloat4(e,t,i,n,r)&&(this.engine.setUInt4(this._uniforms[e],t,i,n,r)||(this._valueCache[e]=null))}setUIntArray(e,t){this._valueCache[e]=null,this.engine.setUIntArray(this._uniforms[e],t)}setUIntArray2(e,t){this._valueCache[e]=null,this.engine.setUIntArray2(this._uniforms[e],t)}setUIntArray3(e,t){this._valueCache[e]=null,this.engine.setUIntArray3(this._uniforms[e],t)}setUIntArray4(e,t){this._valueCache[e]=null,this.engine.setUIntArray4(this._uniforms[e],t)}setArray(e,t){this._valueCache[e]=null,this.engine.setArray(this._uniforms[e],t)}setArray2(e,t){this._valueCache[e]=null,this.engine.setArray2(this._uniforms[e],t)}setArray3(e,t){this._valueCache[e]=null,this.engine.setArray3(this._uniforms[e],t)}setArray4(e,t){this._valueCache[e]=null,this.engine.setArray4(this._uniforms[e],t)}setMatrices(e,t){t&&(this._valueCache[e]=null,this.engine.setMatrices(this._uniforms[e],t))}setMatrix(e,t){this._cacheMatrix(e,t)&&(this.engine.setMatrices(this._uniforms[e],t.asArray())||(this._valueCache[e]=null))}setMatrix3x3(e,t){this._valueCache[e]=null,this.engine.setMatrix3x3(this._uniforms[e],t)}setMatrix2x2(e,t){this._valueCache[e]=null,this.engine.setMatrix2x2(this._uniforms[e],t)}setFloat(e,t){const i=this._valueCache[e];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,n){this._cacheFloat3(e,t,i,n)&&(this.engine.setFloat3(this._uniforms[e],t,i,n)||(this._valueCache[e]=null))}setVector4(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this.engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))}setQuaternion(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this.engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))}setFloat4(e,t,i,n,r){this._cacheFloat4(e,t,i,n,r)&&(this.engine.setFloat4(this._uniforms[e],t,i,n,r)||(this._valueCache[e]=null))}setColor3(e,t){this._cacheFloat3(e,t.r,t.g,t.b)&&(this.engine.setFloat3(this._uniforms[e],t.r,t.g,t.b)||(this._valueCache[e]=null))}setColor4(e,t,i){this._cacheFloat4(e,t.r,t.g,t.b,i)&&(this.engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,i)||(this._valueCache[e]=null))}setDirectColor4(e,t){this._cacheFloat4(e,t.r,t.g,t.b,t.a)&&(this.engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,t.a)||(this._valueCache[e]=null))}_getVertexShaderCode(){return this.vertexShader?this.engine._getShaderSource(this.vertexShader):null}_getFragmentShaderCode(){return this.fragmentShader?this.engine._getShaderSource(this.fragmentShader):null}}const et=new WeakMap,tt={_webGLVersion:2,cachedPipelines:{}};function it(e){let t=et.get(e);if(!t){if(!e)return tt;t={_webGLVersion:e.TEXTURE_BINDING_3D?2:1,_context:e,cachedPipelines:{}},et.set(e,t)}return t}function nt(e,t,i,n,r,s){const a=it(n);s||(s=a._createShaderProgramInjection??st);return s(e,lt(t,"vertex",n,a._contextWasLost),lt(i,"fragment",n,a._contextWasLost),n,r,a.validateShaderPrograms)}function rt(e,t,i,n,r,s=null,a){const o=it(r);a||(a=o._createShaderProgramInjection??st);const l=o._webGLVersion>1?"#version 300 es\n#define WEBGL2 \n":"";return a(e,ot(t,"vertex",n,l,r,o._contextWasLost),ot(i,"fragment",n,l,r,o._contextWasLost),r,s,o.validateShaderPrograms)}function st(e,t,i,n,r=null,s){const a=n.createProgram();if(e.program=a,!a)throw new Error("Unable to create program");return n.attachShader(a,t),n.attachShader(a,i),n.linkProgram(a),e.context=n,e.vertexShader=t,e.fragmentShader=i,e.isParallelCompiled||at(e,n,s),a}function at(e,t,i){const n=e.context,r=e.vertexShader,s=e.fragmentShader,a=e.program;if(!n.getProgramParameter(a,n.LINK_STATUS)){if(!t.getShaderParameter(r,t.COMPILE_STATUS)){const i=t.getShaderInfoLog(r);if(i)throw e.vertexCompilationError=i,new Error("VERTEX SHADER "+i)}if(!t.getShaderParameter(s,t.COMPILE_STATUS)){const i=t.getShaderInfoLog(s);if(i)throw e.fragmentCompilationError=i,new Error("FRAGMENT SHADER "+i)}const i=n.getProgramInfoLog(a);if(i)throw e.programLinkError=i,new Error(i)}if(i){n.validateProgram(a);if(!n.getProgramParameter(a,n.VALIDATE_STATUS)){const t=n.getProgramInfoLog(a);if(t)throw e.programValidationError=t,new Error(t)}}n.deleteShader(r),n.deleteShader(s),e.vertexShader=void 0,e.fragmentShader=void 0,e.onCompiled&&(e.onCompiled(),e.onCompiled=void 0)}function ot(e,t,i,n,r,s){return lt(Ne(e,i,n),t,r,s)}function lt(e,t,i,n){const r=i.createShader("vertex"===t?i.VERTEX_SHADER:i.FRAGMENT_SHADER);if(!r){let e=i.NO_ERROR,r=i.NO_ERROR;for(;(r=i.getError())!==i.NO_ERROR;)e=r;throw new Error(`Something went wrong while creating a gl ${t} shader object. gl error=${e}, gl isContextLost=${i.isContextLost()}, _contextWasLost=${n}`)}return i.shaderSource(r,e),i.compileShader(r),r}function ct(e){const t=e._name,i=e.context;if(t&&i){const e=it(i),n=e.cachedPipelines[t];n?.dispose(),delete e.cachedPipelines[t]}}function ht(e,t,i,n,r,s){if("undefined"!=typeof HTMLElement&&e instanceof HTMLElement){return void n(he(e))}if("source:"===e.substr(0,7))return void n(e.substr(7));if("base64:"===e.substr(0,7)){return void n(window.atob(e.substr(7)))}const a=Je.GetShadersStore(r);if(a[e+t+"Shader"])return void n(a[e+t+"Shader"]);if(i&&a[e+i+"Shader"])return void n(a[e+i+"Shader"]);let o;if(o="."===e[0]||"/"===e[0]||e.indexOf("http")>-1?e:Je.GetShadersRepository(r)+e,!(s=s||Pe))throw new Error("loadFileInjection is not defined");s(o+"."+t.toLowerCase()+".fx",n)}class dt{static get ShadersRepository(){return Je.ShadersRepository}static set ShadersRepository(e){Je.ShadersRepository=e}get onBindObservable(){return this._onBindObservable||(this._onBindObservable=new g),this._onBindObservable}get shaderLanguage(){return this._shaderLanguage}constructor(e,t,i,n=null,r,s=null,a=null,o=null,l=null,c,h="",d=0,u){this.defines="",this.onCompiled=null,this.onError=null,this.onBind=null,this.uniqueId=0,this.onCompileObservable=new g,this.onErrorObservable=new g,this._onBindObservable=null,this._isDisposed=!1,this._refCount=1,this._bonesComputationForcedToCPU=!1,this._uniformBuffersNames={},this._multiTarget=!1,this._samplers={},this._isReady=!1,this._compilationError="",this._allFallbacksProcessed=!1,this._uniforms={},this._key="",this._fallbacks=null,this._vertexSourceCodeOverride="",this._fragmentSourceCodeOverride="",this._transformFeedbackVaryings=null,this._pipelineContext=null,this._vertexSourceCode="",this._fragmentSourceCode="",this._vertexSourceCodeBeforeMigration="",this._fragmentSourceCodeBeforeMigration="",this._rawVertexSourceCode="",this._rawFragmentSourceCode="",this._processCodeAfterIncludes=void 0,this._processFinalCode=null,this.name=e,this._key=h;const f=this._key.replace(/\r/g,"").replace(/\n/g,"|");let _;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<e.uniformBuffersNames.length;t++)this._uniformBuffersNames[e.uniformBuffersNames[t]]=t}this._processFinalCode=e.processFinalCode??null,this._processCodeAfterIncludes=e.processCodeAfterIncludes??void 0,_=e.existingPipelineContext}else this._engine=r,this.defines=null==s?"":s,this._uniformsNames=i.concat(n),this._samplerList=n?n.slice():[],this._attributesNames=t,this._uniformBuffersNamesList=[],this._shaderLanguage=d,this.onError=l,this.onCompiled=o,this._indexParameters=c,this._fallbacks=a;"WEBGL2"===this._engine.shaderPlatformName&&(_=function(e,t){return it(t).cachedPipelines[e]}(f,this._engine._gl)??_),this._attributeLocationByName={},this.uniqueId=dt._UniqueIdSeed++,_?(this._pipelineContext=_,this._pipelineContext.setEngine(this._engine),this._onRenderingStateCompiled(this._pipelineContext),this._pipelineContext.program&&(this._pipelineContext.program.__SPECTOR_rebuildProgram=this._rebuildProgram.bind(this))):this._processShaderCodeAsync(null,!1,null,u)}async _processShaderCodeAsync(e=null,t=!1,i=null,n){n&&await n(),this._processingContext=i||this._engine._getShaderProcessingContext(this._shaderLanguage,!1);!function(e,t,i,n,r,s,a){let o,l;const c=oe()?s?.getHostDocument():null;o="string"==typeof t?t:t.vertexSource?"source:"+t.vertexSource:t.vertexElement?c?.getElementById(t.vertexElement)||t.vertexElement:t.vertex||t,l="string"==typeof t?t:t.fragmentSource?"source:"+t.fragmentSource:t.fragmentElement?c?.getElementById(t.fragmentElement)||t.fragmentElement:t.fragment||t;const h=[void 0,void 0],d=()=>{if(h[0]&&h[1]){e.isFragment=!0;const[o,l]=h;He(l,e,((s,l)=>{a&&(a._fragmentSourceCodeBeforeMigration=l),i&&(s=i("fragment",s));const c=function(e,t,i){return i.processor&&i.processor.finalizeShaders?i.processor.finalizeShaders(e,t,i.processingContext):{vertexCode:e,fragmentCode:t}}(o,s,e);e=null;const h=function(e,t,i,n){return i?{vertexSourceCode:(1===n?"//":"")+"#define SHADER_NAME vertex:"+(i.vertexElement||i.vertex||i.spectorName||i)+"\n"+e,fragmentSourceCode:(1===n?"//":"")+"#define SHADER_NAME fragment:"+(i.fragmentElement||i.fragment||i.spectorName||i)+"\n"+t}:{vertexSourceCode:e,fragmentSourceCode:t}}(c.vertexCode,c.fragmentCode,t,r);n?.(h.vertexSourceCode,h.fragmentSourceCode)}),s)}};ht(o,"Vertex","",(t=>{var n;(n=e).processor&&n.processor.initializeShaders&&n.processor.initializeShaders(n.processingContext),He(t,e,((e,n)=>{a&&(a._rawVertexSourceCode=t,a._vertexSourceCodeBeforeMigration=n),i&&(e=i("vertex",e)),h[0]=e,d()}),s)}),r),ht(l,"Fragment","Pixel",(e=>{a&&(a._rawFragmentSourceCode=e),h[1]=e,d()}),r)}({defines:this.defines.split("\n"),indexParameters:this._indexParameters,isFragment:!1,shouldUseHighPrecisionShader:this._engine._shouldUseHighPrecisionShader,processor:e??this._engine._getShaderProcessor(this._shaderLanguage),supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:Je.GetShadersRepository(this._shaderLanguage),includesShadersStore:Je.GetIncludesShadersStore(this._shaderLanguage),version:(100*this._engine.version).toString(),platformName:this._engine.shaderPlatformName,processingContext:this._processingContext,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer,processCodeAfterIncludes:this._processCodeAfterIncludes},this.name,this._processFinalCode,((e,i)=>{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._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,n){this._isReady=!1,this._vertexSourceCodeOverride=e,this._fragmentSourceCodeOverride=t,this.onError=(e,t)=>{n&&n(t)},this.onCompiled=()=>{const e=this.getEngine().scenes;if(e)for(let t=0;t<e.length;t++)e[t].markAllMaterialsAsDirty(Ze.MATERIAL_AllDirtyFlag);this._pipelineContext._handlesSpectorRebuildCallback?.(i)},this._fallbacks=null,this._prepareEffect()}_onRenderingStateCompiled(e){if(this._pipelineContext=e,this._pipelineContext.setEngine(this._engine),this._attributes=[],this._pipelineContext._fillEffectInformation(this,this._uniformBuffersNames,this._uniformsNames,this._uniforms,this._samplerList,this._samplers,this._attributesNames,this._attributes),this._attributesNames)for(let e=0;e<this._attributesNames.length;e++){const t=this._attributesNames[e];this._attributeLocationByName[t]=this._attributes[e]}this._engine.bindSamplers(this),this._compilationError="",this._isReady=!0,this.onCompiled&&this.onCompiled(this),this.onCompileObservable.notifyObservers(this),this.onCompileObservable.clear(),this._fallbacks&&this._fallbacks.unBindMesh()}_prepareEffect(e=!1){const t=this._pipelineContext;this._isReady=!1;try{const i=!(!this._vertexSourceCodeOverride||!this._fragmentSourceCodeOverride),n=i?null:this.defines,r=i?this._vertexSourceCodeOverride:this._vertexSourceCode,s=i?this._fragmentSourceCodeOverride:this._fragmentSourceCode,a=this._engine;this._pipelineContext=((e,t,i,n)=>{try{const r=e.existingPipelineContext||t(e.shaderProcessingContext);return r._name=e.name,e.name&&e.context&&(it(e.context).cachedPipelines[e.name]=r),i(r,e.vertex,e.fragment,!!e.createAsRaw,"","",e.rebuildRebind,e.defines,e.transformFeedbackVaryings,"",(()=>{n(r,(()=>{e.onRenderingStateCompiled?.(r)}))})),r}catch(e){throw de.Error("Error compiling effect"),e}})({existingPipelineContext:e?t:null,vertex:r,fragment:s,context:"WEBGL2"===a.shaderPlatformName?a._gl:void 0,rebuildRebind:(e,t,i,n)=>this._rebuildProgram(e,t,i,n),defines:n,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 n=i?/FRAGMENT SHADER ERROR: 0:(\d+?):/:/VERTEX SHADER ERROR: 0:(\d+?):/;let r=null;if(t&&e){const s=t.match(n);if(s&&2===s.length){const t=parseInt(s[1]),n=e.split("\n",-1);n.length>=t&&(r=`Offending line [${t}] in ${i?"fragment":"vertex"} code: ${n[t-1]}`)}}return[e,r]}_processCompilationErrors(e,t=null){this._compilationError=e.message;const i=this._attributesNames,n=this._fallbacks;if(de.Error("Unable to compile effect:"),de.Error("Uniforms: "+this._uniformsNames.map((function(e){return" "+e}))),de.Error("Attributes: "+i.map((function(e){return" "+e}))),de.Error("Defines:\n"+this.defines),dt.LogShaderCodeOnCompilationError){let e=null,t=null,i=null;this._pipelineContext?._getVertexShaderCode()&&([i,e]=this._getShaderCodeAndErrorLine(this._pipelineContext._getVertexShaderCode(),this._compilationError,!1),i&&(de.Error("Vertex code:"),de.Error(i))),this._pipelineContext?._getFragmentShaderCode()&&([i,t]=this._getShaderCodeAndErrorLine(this._pipelineContext?._getFragmentShaderCode(),this._compilationError,!0),i&&(de.Error("Fragment code:"),de.Error(i))),e&&de.Error(e),t&&de.Error(t)}de.Error("Error: "+this._compilationError);const r=()=>{this.onError&&this.onError(this,this._compilationError),this.onErrorObservable.notifyObservers(this)};t&&(this._pipelineContext=t,this._isReady=!0,r()),n?(this._pipelineContext=null,n.hasMoreFallbacks?(this._allFallbacksProcessed=!1,de.Error("Trying next fallback."),this.defines=n.reduce(this.defines,this),this._prepareEffect()):(this._allFallbacksProcessed=!0,r(),this.onErrorObservable.clear(),this._fallbacks&&this._fallbacks.unBindMesh())):(this._allFallbacksProcessed=!0,t||r())}get isSupported(){return""===this._compilationError}_bindTexture(e,t){this._engine._bindTexture(this._samplers[e],t,e)}setTexture(e,t){this._engine.setTexture(this._samplers[e],this._uniforms[e],t,e)}setTextureArray(e,t){const i=e+"Ex";if(-1===this._samplerList.indexOf(i+"0")){const n=this._samplerList.indexOf(e);for(let e=1;e<t.length;e++){const t=i+(e-1).toString();this._samplerList.splice(n+e,0,t)}let r=0;for(const e of this._samplerList)this._samplers[e]=r,r+=1}this._engine.setTextureArray(this._samplers[e],this._uniforms[e],t,e)}bindUniformBuffer(e,t){const i=this._uniformBuffersNames[t];void 0===i||dt._BaseCache[i]===e&&this._engine._features.useUBOBindingCache||(dt._BaseCache[i]=e,this._engine.bindUniformBufferBase(e,i,t))}bindUniformBlock(e,t){this._engine.bindUniformBlock(this._pipelineContext,e,t)}setInt(e,t){return this._pipelineContext.setInt(e,t),this}setInt2(e,t,i){return this._pipelineContext.setInt2(e,t,i),this}setInt3(e,t,i,n){return this._pipelineContext.setInt3(e,t,i,n),this}setInt4(e,t,i,n,r){return this._pipelineContext.setInt4(e,t,i,n,r),this}setIntArray(e,t){return this._pipelineContext.setIntArray(e,t),this}setIntArray2(e,t){return this._pipelineContext.setIntArray2(e,t),this}setIntArray3(e,t){return this._pipelineContext.setIntArray3(e,t),this}setIntArray4(e,t){return this._pipelineContext.setIntArray4(e,t),this}setUInt(e,t){return this._pipelineContext.setUInt(e,t),this}setUInt2(e,t,i){return this._pipelineContext.setUInt2(e,t,i),this}setUInt3(e,t,i,n){return this._pipelineContext.setUInt3(e,t,i,n),this}setUInt4(e,t,i,n,r){return this._pipelineContext.setUInt4(e,t,i,n,r),this}setUIntArray(e,t){return this._pipelineContext.setUIntArray(e,t),this}setUIntArray2(e,t){return this._pipelineContext.setUIntArray2(e,t),this}setUIntArray3(e,t){return this._pipelineContext.setUIntArray3(e,t),this}setUIntArray4(e,t){return this._pipelineContext.setUIntArray4(e,t),this}setFloatArray(e,t){return this._pipelineContext.setArray(e,t),this}setFloatArray2(e,t){return this._pipelineContext.setArray2(e,t),this}setFloatArray3(e,t){return this._pipelineContext.setArray3(e,t),this}setFloatArray4(e,t){return this._pipelineContext.setArray4(e,t),this}setArray(e,t){return this._pipelineContext.setArray(e,t),this}setArray2(e,t){return this._pipelineContext.setArray2(e,t),this}setArray3(e,t){return this._pipelineContext.setArray3(e,t),this}setArray4(e,t){return this._pipelineContext.setArray4(e,t),this}setMatrices(e,t){return this._pipelineContext.setMatrices(e,t),this}setMatrix(e,t){return this._pipelineContext.setMatrix(e,t),this}setMatrix3x3(e,t){return this._pipelineContext.setMatrix3x3(e,t),this}setMatrix2x2(e,t){return this._pipelineContext.setMatrix2x2(e,t),this}setFloat(e,t){return this._pipelineContext.setFloat(e,t),this}setBool(e,t){return this._pipelineContext.setInt(e,t?1:0),this}setVector2(e,t){return this._pipelineContext.setVector2(e,t),this}setFloat2(e,t,i){return this._pipelineContext.setFloat2(e,t,i),this}setVector3(e,t){return this._pipelineContext.setVector3(e,t),this}setFloat3(e,t,i,n){return this._pipelineContext.setFloat3(e,t,i,n),this}setVector4(e,t){return this._pipelineContext.setVector4(e,t),this}setQuaternion(e,t){return this._pipelineContext.setQuaternion(e,t),this}setFloat4(e,t,i,n,r){return this._pipelineContext.setFloat4(e,t,i,n,r),this}setColor3(e,t){return this._pipelineContext.setColor3(e,t),this}setColor4(e,t,i){return this._pipelineContext.setColor4(e,t,i),this}setDirectColor4(e,t){return this._pipelineContext.setDirectColor4(e,t),this}dispose(){this._refCount--,this._refCount>0||(this._pipelineContext&&ct(this._pipelineContext),this._engine._releaseEffect(this),this._isDisposed=!0)}static RegisterShader(e,t,i,n=0){t&&(Je.GetShadersStore(n)[`${e}PixelShader`]=t),i&&(Je.GetShadersStore(n)[`${e}VertexShader`]=i)}static ResetCache(){dt._BaseCache={}}}dt.LogShaderCodeOnCompilationError=!0,dt._UniqueIdSeed=0,dt._BaseCache={},dt.ShadersStore=Je.ShadersStore,dt.IncludesShadersStore=Je.IncludesShadersStore;class ut{constructor(e=!0){this._isDepthTestDirty=!1,this._isDepthMaskDirty=!1,this._isDepthFuncDirty=!1,this._isCullFaceDirty=!1,this._isCullDirty=!1,this._isZOffsetDirty=!1,this._isFrontFaceDirty=!1,e&&this.reset()}get isDirty(){return this._isDepthFuncDirty||this._isDepthTestDirty||this._isDepthMaskDirty||this._isCullFaceDirty||this._isCullDirty||this._isZOffsetDirty||this._isFrontFaceDirty}get zOffset(){return this._zOffset}set zOffset(e){this._zOffset!==e&&(this._zOffset=e,this._isZOffsetDirty=!0)}get zOffsetUnits(){return this._zOffsetUnits}set zOffsetUnits(e){this._zOffsetUnits!==e&&(this._zOffsetUnits=e,this._isZOffsetDirty=!0)}get cullFace(){return this._cullFace}set cullFace(e){this._cullFace!==e&&(this._cullFace=e,this._isCullFaceDirty=!0)}get cull(){return this._cull}set cull(e){this._cull!==e&&(this._cull=e,this._isCullDirty=!0)}get depthFunc(){return this._depthFunc}set depthFunc(e){this._depthFunc!==e&&(this._depthFunc=e,this._isDepthFuncDirty=!0)}get depthMask(){return this._depthMask}set depthMask(e){this._depthMask!==e&&(this._depthMask=e,this._isDepthMaskDirty=!0)}get depthTest(){return this._depthTest}set depthTest(e){this._depthTest!==e&&(this._depthTest=e,this._isDepthTestDirty=!0)}get frontFace(){return this._frontFace}set frontFace(e){this._frontFace!==e&&(this._frontFace=e,this._isFrontFaceDirty=!0)}reset(){this._depthMask=!0,this._depthTest=!0,this._depthFunc=null,this._cullFace=null,this._cull=null,this._zOffset=0,this._zOffsetUnits=0,this._frontFace=null,this._isDepthTestDirty=!0,this._isDepthMaskDirty=!0,this._isDepthFuncDirty=!1,this._isCullFaceDirty=!1,this._isCullDirty=!1,this._isZOffsetDirty=!0,this._isFrontFaceDirty=!1}apply(e){this.isDirty&&(this._isCullDirty&&(this.cull?e.enable(e.CULL_FACE):e.disable(e.CULL_FACE),this._isCullDirty=!1),this._isCullFaceDirty&&(e.cullFace(this.cullFace),this._isCullFaceDirty=!1),this._isDepthMaskDirty&&(e.depthMask(this.depthMask),this._isDepthMaskDirty=!1),this._isDepthTestDirty&&(this.depthTest?e.enable(e.DEPTH_TEST):e.disable(e.DEPTH_TEST),this._isDepthTestDirty=!1),this._isDepthFuncDirty&&(e.depthFunc(this.depthFunc),this._isDepthFuncDirty=!1),this._isZOffsetDirty&&(this.zOffset||this.zOffsetUnits?(e.enable(e.POLYGON_OFFSET_FILL),e.polygonOffset(this.zOffset,this.zOffsetUnits)):e.disable(e.POLYGON_OFFSET_FILL),this._isZOffsetDirty=!1),this._isFrontFaceDirty&&(e.frontFace(this.frontFace),this._isFrontFaceDirty=!1))}}class ft{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))}}class _t{constructor(){this.reset()}reset(){this.enabled=!1,this.mask=255,this.func=_t.ALWAYS,this.funcRef=1,this.funcMask=255,this.opStencilFail=_t.KEEP,this.opDepthFail=_t.KEEP,this.opStencilDepthPass=_t.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}}_t.ALWAYS=Ze.ALWAYS,_t.KEEP=Ze.KEEP,_t.REPLACE=Ze.REPLACE;class mt{constructor(){this._blendFunctionParameters=new Array(4),this._blendEquationParameters=new Array(2),this._blendConstants=new Array(4),this._isBlendConstantsDirty=!1,this._alphaBlend=!1,this._isAlphaBlendDirty=!1,this._isBlendFunctionParametersDirty=!1,this._isBlendEquationParametersDirty=!1,this.reset()}get isDirty(){return this._isAlphaBlendDirty||this._isBlendFunctionParametersDirty||this._isBlendEquationParametersDirty}get alphaBlend(){return this._alphaBlend}set alphaBlend(e){this._alphaBlend!==e&&(this._alphaBlend=e,this._isAlphaBlendDirty=!0)}setAlphaBlendConstants(e,t,i,n){this._blendConstants[0]===e&&this._blendConstants[1]===t&&this._blendConstants[2]===i&&this._blendConstants[3]===n||(this._blendConstants[0]=e,this._blendConstants[1]=t,this._blendConstants[2]=i,this._blendConstants[3]=n,this._isBlendConstantsDirty=!0)}setAlphaBlendFunctionParameters(e,t,i,n){this._blendFunctionParameters[0]===e&&this._blendFunctionParameters[1]===t&&this._blendFunctionParameters[2]===i&&this._blendFunctionParameters[3]===n||(this._blendFunctionParameters[0]=e,this._blendFunctionParameters[1]=t,this._blendFunctionParameters[2]=i,this._blendFunctionParameters[3]=n,this._isBlendFunctionParametersDirty=!0)}setAlphaEquationParameters(e,t){this._blendEquationParameters[0]===e&&this._blendEquationParameters[1]===t||(this._blendEquationParameters[0]=e,this._blendEquationParameters[1]=t,this._isBlendEquationParametersDirty=!0)}reset(){this._alphaBlend=!1,this._blendFunctionParameters[0]=null,this._blendFunctionParameters[1]=null,this._blendFunctionParameters[2]=null,this._blendFunctionParameters[3]=null,this._blendEquationParameters[0]=null,this._blendEquationParameters[1]=null,this._blendConstants[0]=null,this._blendConstants[1]=null,this._blendConstants[2]=null,this._blendConstants[3]=null,this._isAlphaBlendDirty=!0,this._isBlendFunctionParametersDirty=!1,this._isBlendEquationParametersDirty=!1,this._isBlendConstantsDirty=!1}apply(e){this.isDirty&&(this._isAlphaBlendDirty&&(this._alphaBlend?e.enable(e.BLEND):e.disable(e.BLEND),this._isAlphaBlendDirty=!1),this._isBlendFunctionParametersDirty&&(e.blendFuncSeparate(this._blendFunctionParameters[0],this._blendFunctionParameters[1],this._blendFunctionParameters[2],this._blendFunctionParameters[3]),this._isBlendFunctionParametersDirty=!1),this._isBlendEquationParametersDirty&&(e.blendEquationSeparate(this._blendEquationParameters[0],this._blendEquationParameters[1]),this._isBlendEquationParametersDirty=!1),this._isBlendConstantsDirty&&(e.blendColor(this._blendConstants[0],this._blendConstants[1],this._blendConstants[2],this._blendConstants[3]),this._isBlendConstantsDirty=!1))}}class pt{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=Ze.TEXTURE_WRAP_ADDRESSMODE,t=Ze.TEXTURE_WRAP_ADDRESSMODE,i=Ze.TEXTURE_WRAP_ADDRESSMODE,n=1,r=Ze.TEXTURE_BILINEAR_SAMPLINGMODE,s=0){return this._cachedWrapU=e,this._cachedWrapV=t,this._cachedWrapR=i,this._cachedAnisotropicFilteringLevel=n,this.samplingMode=r,this._comparisonFunction=s,this}compareSampler(e){return this._cachedWrapU===e._cachedWrapU&&this._cachedWrapV===e._cachedWrapV&&this._cachedWrapR===e._cachedWrapR&&this._cachedAnisotropicFilteringLevel===e._cachedAnisotropicFilteringLevel&&this.samplingMode===e.samplingMode&&this._comparisonFunction===e._comparisonFunction&&this._useMipMaps===e._useMipMaps}}var gt;!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"}(gt||(gt={}));class Et extends pt{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 g,this.onErrorObservable=new g,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=Et._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: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 n=i.indexOf(this);-1!==n&&i.splice(n,1),n=i.indexOf(e),-1===n&&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)}}function Tt(e,t){return e.endsWith(".dds")?Promise.resolve().then((function(){return Nd})).then((e=>new e._DDSTextureLoader)):e.endsWith(".basis")?Promise.resolve().then((function(){return Hd})).then((e=>new e._BasisTextureLoader)):e.endsWith(".env")?Promise.resolve().then((function(){return Ea})).then((e=>new e._ENVTextureLoader)):e.endsWith(".hdr")?Promise.resolve().then((function(){return Zd})).then((e=>new e._HDRTextureLoader)):e.endsWith(".ktx")||e.endsWith(".ktx2")||"image/ktx"===t||"image/ktx2"===t?Promise.resolve().then((function(){return iu})).then((e=>new e._KTXTextureLoader)):e.endsWith(".tga")?Promise.resolve().then((function(){return au})).then((e=>new e._TGATextureLoader)):null}function At(e,t){if(oe()){const{requestAnimationFrame:i}=t||window;if("function"==typeof i)return i(e)}else if("function"==typeof requestAnimationFrame)return requestAnimationFrame(e);return setTimeout(e,16)}Et._Counter=0;class vt{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?Ze.GEQUAL:Ze.LEQUAL)}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()}dt.ResetCache()}_rebuildGraphicsResources(){this.wipeCaches(!0),this._rebuildEffects(),this._rebuildComputeEffects?.(),this._rebuildBuffers(),this._rebuildInternalTextures(),this._rebuildTextures(),this._rebuildRenderTargetWrappers(),this.wipeCaches(!0)}_flagContextRestored(){de.Warn(this.name+" context successfully restored."),this.onContextRestoredObservable.notifyObservers(this),this._contextWasLost=!1}_restoreEngineAfterContextLost(e){setTimeout((async()=>{this._clearEmptyResources();const t=this._depthCullingState.depthTest,i=this._depthCullingState.depthFunc,n=this._depthCullingState.depthMask,r=this._stencilState.stencilTest;await e(),this._rebuildGraphicsResources(),this._depthCullingState.depthTest=t,this._depthCullingState.depthFunc=i,this._depthCullingState.depthMask=n,this._stencilState.stencilTest=r,this._flagContextRestored()}),0)}get isDisposed(){return this._isDisposed}get snapshotRendering(){return!1}set snapshotRendering(e){}get snapshotRenderingMode(){return Ze.SNAPSHOTRENDERING_STANDARD}set snapshotRenderingMode(e){}getClassName(){return"AbstractEngine"}get emptyTexture(){return this._emptyTexture||(this._emptyTexture=this.createRawTexture(new Uint8Array(4),1,1,Ze.TEXTUREFORMAT_RGBA,!1,!1,Ze.TEXTURE_NEAREST_SAMPLINGMODE)),this._emptyTexture}get emptyTexture3D(){return this._emptyTexture3D||(this._emptyTexture3D=this.createRawTexture3D(new Uint8Array(4),1,1,1,Ze.TEXTUREFORMAT_RGBA,!1,!1,Ze.TEXTURE_NEAREST_SAMPLINGMODE)),this._emptyTexture3D}get emptyTexture2DArray(){return this._emptyTexture2DArray||(this._emptyTexture2DArray=this.createRawTexture2DArray(new Uint8Array(4),1,1,1,Ze.TEXTUREFORMAT_RGBA,!1,!1,Ze.TEXTURE_NEAREST_SAMPLINGMODE)),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,Ze.TEXTUREFORMAT_RGBA,Ze.TEXTURETYPE_UNSIGNED_INT,!1,!1,Ze.TEXTURE_NEAREST_SAMPLINGMODE)}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,oe()){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<this._activeRenderLoops.length;e++){(0,this._activeRenderLoops[e])()}}_renderViews(){return!1}_queueNewFrame(e,t){return At(e,t)}runRenderLoop(e){-1===this._activeRenderLoops.indexOf(e)&&(this._activeRenderLoops.push(e),1===this._activeRenderLoops.length&&0===this._frameHandler&&(this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow())))}getDepthBuffer(){return this._depthCullingState.depthTest}setDepthBuffer(e){this._depthCullingState.depthTest=e}setZOffset(e){this._depthCullingState.zOffset=this.useReverseDepthBuffer?-e:e}getZOffset(){const e=this._depthCullingState.zOffset;return this.useReverseDepthBuffer?-e:e}setZOffsetUnits(e){this._depthCullingState.zOffsetUnits=this.useReverseDepthBuffer?-e:e}getZOffsetUnits(){const e=this._depthCullingState.zOffsetUnits;return this.useReverseDepthBuffer?-e:e}getHostWindow(){return oe()?this._renderingCanvas&&this._renderingCanvas.ownerDocument&&this._renderingCanvas.ownerDocument.defaultView?this._renderingCanvas.ownerDocument.defaultView:window:null}get compatibilityMode(){return this._compatibilityMode}set compatibilityMode(e){this._compatibilityMode=!0}_rebuildTextures(){for(const e of this.scenes)e._rebuildTextures();for(const e of this._virtualScenes)e._rebuildTextures()}_releaseRenderTargetWrapper(e){const t=this._renderTargetWrapperCache.indexOf(e);-1!==t&&this._renderTargetWrapperCache.splice(t,1)}get currentViewport(){return this._cachedViewport}setViewport(e,t,i){const n=t||this.getRenderWidth(),r=i||this.getRenderHeight(),s=e.x||0,a=e.y||0;this._cachedViewport=e,this._viewport(s*n,a*r,n*e.width,r*e.height)}createCanvasImage(){return document.createElement("img")}get description(){let e=this.name+this.version;return this._caps.parallelShaderCompile&&(e+=" - Parallel shader compilation"),e}_createTextureBase(e,t,i,n,r=Ze.TEXTURE_TRILINEAR_SAMPLINGMODE,s=null,a=null,o,l,c=null,h=null,d=null,u=null,f,_,m){const p="data:"===(e=e||"").substr(0,5),g="blob:"===e.substr(0,5),E=p&&-1!==e.indexOf(";base64,"),T=h||new Et(this,1);T!==h&&(T.label=e.substring(0,60));const A=e;!this._transformTextureUrl||E||h||c||(e=this._transformTextureUrl(e)),A!==e&&(T._originalUrl=A);const v=e.lastIndexOf(".");let R=u||(v>-1?e.substring(v).toLowerCase():"");R.indexOf("?")>-1&&(R=R.split("?")[0]);const S=Tt(R,f);n&&n.addPendingData(T),T.url=e,T.generateMipMaps=!t,T.samplingMode=r,T.invertY=i,T._useSRGBBuffer=this._getUseSRGBBuffer(!!m,t),this._doNotHandleContextLost||(T._buffer=c);let I=null;s&&!h&&(I=T.onLoadedObservable.add(s)),h||this._internalTexturesCache.push(T);const C=(i,h)=>{n&&n.removePendingData(T),e===A?(I&&T.onLoadedObservable.remove(I),y.UseFallbackTexture&&e!==y.FallbackTexture&&this._createTextureBase(y.FallbackTexture,t,T.invertY,n,r,null,a,o,l,c,T),i=(i||"Unknown error")+(y.UseFallbackTexture?" - Fallback texture was used":""),T.onErrorObservable.notifyObservers({message:i,exception:h}),a&&a(i,h)):(de.Warn(`Failed to load ${e}, falling back to ${A}`),this._createTextureBase(A,t,T.invertY,n,r,s,a,o,l,c,T,d,u,f,_,m))};if(S){const t=async e=>{(await S).loadData(e,T,((e,t,i,s,a,l)=>{l?C("TextureLoader failed to load data"):o(T,R,n,{width:e,height:t},T.invertY,!i,s,(()=>(a(),!1)),r)}),_)};c?c instanceof ArrayBuffer?t(new Uint8Array(c)):ArrayBuffer.isView(c)?t(c):a&&a("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)=>{C("Unable to load "+(e&&e.responseURL,t))}))}else{const i=e=>{g&&!this._doNotHandleContextLost&&(T._buffer=e),o(T,R,n,e,T.invertY,t,!1,l,r)};!p||E?c&&("string"==typeof c.decoding||c.close)?i(c):vt._FileToolsLoadImage(e||"",i,C,n?n.offlineProvider:null,f,T.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):"string"==typeof c||c instanceof ArrayBuffer||ArrayBuffer.isView(c)||c instanceof Blob?vt._FileToolsLoadImage(c,i,C,n?n.offlineProvider:null,f,T.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):c&&i(c)}return T}_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:ce()?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.21.5"}static get Version(){return"7.21.5"}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 ut,this._stencilStateComposer=new ft,this._stencilState=new _t,this._alphaState=new mt,this._alphaMode=Ze.ALPHA_ADD,this._alphaEquation=Ze.ALPHA_DISABLE,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 g,this.onCanvasFocusObservable=new g,this.onNewSceneAddedObservable=new g,this.onResizeObservable=new g,this.onCanvasPointerOutObservable=new g,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=Ze.RENDERPASS_MAIN,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 g,this.renderEvenInBackground=!0,this.preventCacheWipeBetweenFrames=!1,this._frameHandler=0,this._activeRenderLoops=new Array,this._windowIsBackground=!1,this._boundRenderFunction=()=>this._renderLoop(),this.onBeforeShaderCompilationObservable=new g,this.onAfterShaderCompilationObservable=new g,this.onBeginFrameObservable=new g,this.onEndFrameObservable=new g,this._transformTextureUrl=null,this._uniformBuffers=new Array,this._storageBuffers=new Array,this._highPrecisionShadersAllowed=!0,this.onContextLostObservable=new g,this.onContextRestoredObservable=new g,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 g,y.Instances.push(this),this.startTime=_e.Now,this._stencilStateComposer.stencilGlobal=this._stencilState,b.SetMatrixPrecision(!!t.useHighPrecisionMatrix),le()&&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 n=oe()&&window.devicePixelRatio||1,r=t.limitDeviceRatio||n;i=i||t.adaptToDeviceRatio||!1,this._hardwareScalingLevel=i?1/Math.min(r,n):1,this._lastDevicePixelRatio=n,this._creationOptions=t}resize(e=!1){let t,i;if(this.adaptToDeviceRatio){const e=oe()&&window.devicePixelRatio||1,t=this._lastDevicePixelRatio/e;this._lastDevicePixelRatio=e,this._hardwareScalingLevel*=t}if(oe()&&ce())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<this.scenes.length;e++){const t=this.scenes[e];for(let e=0;e<t.cameras.length;e++){t.cameras[e]._currentRenderId=0}}this.onResizeObservable.hasObservers()&&this.onResizeObservable.notifyObservers(this)}return!0}createRawTexture(e,t,i,n,r,s,a,o,l,c,h){throw Y("engine.rawTexture")}createRawCubeTexture(e,t,i,n,r,s,a,o){throw Y("engine.rawTexture")}createRawTexture3D(e,t,i,n,r,s,a,o,l,c,h){throw Y("engine.rawTexture")}createRawTexture2DArray(e,t,i,n,r,s,a,o,l,c,h){throw Y("engine.rawTexture")}_sharedInit(e){this._renderingCanvas=e}_setupMobileChecks(){navigator&&navigator.userAgent&&(this._checkForMobile=()=>{const e=navigator.userAgent;this.hostInformation.isMobile=-1!==e.indexOf("Mobile")||-1!==e.indexOf("Mac")&&ce()&&"ontouchend"in document},this._checkForMobile(),oe()&&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 vt._CreateCanvas(e,t)}static _FileToolsLoadImage(e,t,i,n,r,s){throw Y("FileTools")}_loadFile(e,t,i,n,r,s){const a=Pe(e,t,i,n,r,s);return this._activeRequests.push(a),a.onCompleteObservable.add((()=>{const e=this._activeRequests.indexOf(a);-1!==e&&this._activeRequests.splice(e,1)})),a}static _FileToolsLoadFile(e,t,i,n,r,s){if(De.loadFile)return De.loadFile(e,t,i,n,r,s);throw Y("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?.(),dt.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(),oe()&&window.removeEventListener("resize",this._checkForMobile);const e=y.Instances.indexOf(this);e>=0&&y.Instances.splice(e,1),y.Instances.length||(y.OnEnginesDisposedObservable.notifyObservers(this),y.OnEnginesDisposedObservable.clear()),this.onBeginFrameObservable.clear(),this.onEndFrameObservable.clear()}static DefaultLoadingScreenFactory(e){throw Y("LoadingScreen")}static MarkAllMaterialsAsDirty(e,t){for(let i=0;i<y.Instances.length;i++){const n=y.Instances[i];for(let i=0;i<n.scenes.length;i++)n.scenes[i].markAllMaterialsAsDirty(e,t)}}}vt._RenderPassIdCounter=0,vt._RescalePostProcessFactory=null,vt.CollisionsEpsilon=.001,vt.QueueNewFrame=At;const Rt=new RegExp(/^data:([^,]+\/[^,]+)?;base64,/i);class St extends Te{constructor(e,t){super(e,Ee.LoadFileError),this.name="LoadFileError",ge._setPrototypeOf(this,St.prototype),t instanceof me?this.request=t:this.file=t}}class It extends Te{constructor(e,t){super(e,Ee.RequestFileError),this.request=t,this.name="RequestFileError",ge._setPrototypeOf(this,It.prototype)}}class Ct extends Te{constructor(e,t){super(e,Ee.ReadFileError),this.file=t,this.name="ReadFileError",ge._setPrototypeOf(this,Ct.prototype)}}const Mt={DefaultRetryStrategy:class{static ExponentialBackoff(e=3,t=500){return(i,n,r)=>0!==n.status||r>=e||-1!==i.indexOf("file:")?-1:Math.pow(2,r)*t}}.ExponentialBackoff(),BaseUrl:"",CorsBehavior:"anonymous",PreprocessUrl:e=>e,ScriptBaseUrl:"",ScriptPreprocessUrl:e=>e,CleanUrl:e=>e=e.replace(/#/gm,"%23")},xt=(e,t)=>{if((!e||0!==e.indexOf("data:"))&&Mt.CorsBehavior)if("string"==typeof Mt.CorsBehavior||Mt.CorsBehavior instanceof String)t.crossOrigin=Mt.CorsBehavior;else{const i=Mt.CorsBehavior(e);i&&(t.crossOrigin=i)}},bt=(e,t,i,n,r="",s)=>{const a=y.LastCreatedEngine;if("undefined"==typeof HTMLImageElement&&!a?._features.forceBitmapOverHTMLImageElement)return i("LoadImage is only supported in web or BabylonNative environments."),null;let o,l=!1;e instanceof ArrayBuffer||ArrayBuffer.isView(e)?"undefined"!=typeof Blob&&"undefined"!=typeof URL?(o=URL.createObjectURL(new Blob([e],{type:r})),l=!0):o=`data:${r};base64,`+Ae(e):e instanceof Blob?(o=URL.createObjectURL(e),l=!0):(o=Mt.CleanUrl(e),o=Mt.PreprocessUrl(o));const c=t=>{if(i){const n=o||e.toString();i(`Error while trying to load image: ${0===n.indexOf("http")||n.length<=128?n:n.slice(0,128)+"..."}`,t)}};if(a?._features.forceBitmapOverHTMLImageElement)return Ot(o,(n=>{a.createImageBitmap(new Blob([n],{type:r}),{premultiplyAlpha:"none",...s}).then((e=>{t(e),l&&URL.revokeObjectURL(o)})).catch((t=>{i&&i("Error while trying to load image: "+e,t)}))}),void 0,n||void 0,!0,((e,t)=>{c(t)})),null;const h=new Image;xt(o,h);const d=[],u=()=>{d.forEach((e=>{e.target.removeEventListener(e.name,e.handler)})),d.length=0};d.push({target:h,name:"load",handler:()=>{u(),t(h),l&&h.src&&URL.revokeObjectURL(h.src)}}),d.push({target:h,name:"error",handler:e=>{u(),c(e),l&&h.src&&URL.revokeObjectURL(h.src)}}),d.push({target:document,name:"securitypolicyviolation",handler:e=>{if(e.blockedURI!==h.src)return;u();const t=new Error(`CSP violation of policy ${e.effectiveDirective} ${e.blockedURI}. Current policy is ${e.originalPolicy}`);y.UseFallbackTexture=!1,c(t),l&&h.src&&URL.revokeObjectURL(h.src),h.src=""}}),d.forEach((e=>{e.target.addEventListener(e.name,e.handler)}));const f="blob:"===o.substring(0,5),_="data:"===o.substring(0,5),m=()=>{f||_||!me.IsCustomRequestAvailable?h.src=o:Ot(o,((e,t,i)=>{const n=new Blob([e],{type:!r&&i?i:r}),s=URL.createObjectURL(n);l=!0,h.src=s}),void 0,n||void 0,!0,((e,t)=>{c(t)}))},p=()=>{n&&n.loadImage(o,h)};if(!f&&!_&&n&&n.enableTexturesOffline)n.open(p,m);else{if(-1!==o.indexOf("file:")){const e=decodeURIComponent(o.substring(5).toLowerCase());if(pe.FilesToLoad[e]&&"undefined"!=typeof URL){try{let t;try{t=URL.createObjectURL(pe.FilesToLoad[e])}catch(i){t=URL.createObjectURL(pe.FilesToLoad[e])}h.src=t,l=!0}catch(e){h.src=""}return h}}m()}return h},yt=(e,t,i,n,r)=>{const s=new FileReader,a={onCompleteObservable:new g,abort:()=>s.abort()};return s.onloadend=()=>a.onCompleteObservable.notifyObservers(a),r&&(s.onerror=()=>{r(new Ct(`Unable to read ${e.name}`,e))}),s.onload=e=>{t(e.target.result)},i&&(s.onprogress=i),n?s.readAsArrayBuffer(e):s.readAsText(e),a},Ot=(e,t,i,n,r,s,a)=>{if(e.name)return yt(e,t,i,r,s?e=>{s(void 0,e)}:void 0);const o=e;if(-1!==o.indexOf("file:")){let e=decodeURIComponent(o.substring(5).toLowerCase());0===e.indexOf("./")&&(e=e.substring(2));const n=pe.FilesToLoad[e];if(n)return yt(n,t,i,r,s?e=>s(void 0,new St(e.message,e.file)):void 0)}const{match:l,type:c}=Lt(o);if(l){const e={onCompleteObservable:new g,abort:()=>()=>{}};try{const e=r?Ft(o):wt(o);t(e,void 0,c)}catch(e){s?s(void 0,e):de.Error(e.message||"Failed to parse the Data URL")}return Qe.SetImmediate((()=>{e.onCompleteObservable.notifyObservers(e)})),e}return Dt(o,((e,i)=>{t(e,i?.responseURL,i?.getResponseHeader("content-type"))}),i,n,r,s?e=>{s(e.request,new St(e.message,e.request))}:void 0,a)},Dt=(e,t,i,n,r,s,a)=>{e=Mt.CleanUrl(e),e=Mt.PreprocessUrl(e);const o=Mt.BaseUrl+e;let l=!1;const c={onCompleteObservable:new g,abort:()=>l=!0},h=()=>{let e,n=new me,h=null;const d=()=>{n&&(i&&n.removeEventListener("progress",i),e&&n.removeEventListener("readystatechange",e),n.removeEventListener("loadend",u))};let u=()=>{d(),c.onCompleteObservable.notifyObservers(c),c.onCompleteObservable.clear(),i=void 0,e=null,u=null,s=void 0,a=void 0,t=void 0};c.abort=()=>{l=!0,u&&u(),n&&n.readyState!==(XMLHttpRequest.DONE||4)&&n.abort(),null!==h&&(clearTimeout(h),h=null),n=null};const f=e=>{const t=e.message||"Unknown error";s&&n?s(new It(t,n)):de.Error(t)},_=c=>{if(n){if(n.open("GET",o),a)try{a(n)}catch(e){return void f(e)}r&&(n.responseType="arraybuffer"),i&&n.addEventListener("progress",i),u&&n.addEventListener("loadend",u),e=()=>{if(!l&&n&&n.readyState===(XMLHttpRequest.DONE||4)){if(e&&n.removeEventListener("readystatechange",e),n.status>=200&&n.status<300||0===n.status&&(!oe()||Nt())){try{t&&t(r?n.response:n.responseText,n)}catch(e){f(e)}return}const i=Mt.DefaultRetryStrategy;if(i){const e=i(o,n,c);if(-1!==e)return d(),n=new me,void(h=setTimeout((()=>_(c+1)),e))}const a=new It("Error status: "+n.status+" "+n.statusText+" - Unable to load "+o,n);s&&s(a)}},n.addEventListener("readystatechange",e),n.send()}};_(0)};if(n&&n.enableSceneOffline){const a=e=>{e&&e.status>400?s&&s(e):h()},o=()=>{n&&n.loadFile(Mt.BaseUrl+e,(e=>{!l&&t&&t(e),c.onCompleteObservable.notifyObservers(c)}),i?e=>{!l&&i&&i(e)}:void 0,a,r)};n.open(o,a)}else h();return c},Nt=()=>"undefined"!=typeof location&&"file:"===location.protocol,Pt=e=>Rt.test(e),Lt=e=>{const t=Rt.exec(e);if(null===t||0===t.length)return{match:!1,type:""};return{match:!0,type:t[0].replace("data:","").replace("base64,","")}};function Ft(e){return(e=>{const t=ve(e),i=t.length,n=new Uint8Array(new ArrayBuffer(i));for(let e=0;e<i;e++)n[e]=t.charCodeAt(e);return n.buffer})(e.split(",")[1])}const wt=e=>ve(e.split(",")[1]);let Ut;vt._FileToolsLoadImage=bt,De.loadFile=Ot,je.loadFile=Ot;((e,t,i,n,r,s,a,o,l,c)=>{Ut={DecodeBase64UrlToBinary:e,DecodeBase64UrlToString:t,DefaultRetryStrategy:i.DefaultRetryStrategy,BaseUrl:i.BaseUrl,CorsBehavior:i.CorsBehavior,PreprocessUrl:i.PreprocessUrl,IsBase64DataUrl:n,IsFileURL:r,LoadFile:s,LoadImage:a,ReadFile:o,RequestFile:l,SetCorsBehavior:c},Object.defineProperty(Ut,"DefaultRetryStrategy",{get:function(){return i.DefaultRetryStrategy},set:function(e){i.DefaultRetryStrategy=e}}),Object.defineProperty(Ut,"BaseUrl",{get:function(){return i.BaseUrl},set:function(e){i.BaseUrl=e}}),Object.defineProperty(Ut,"PreprocessUrl",{get:function(){return i.PreprocessUrl},set:function(e){i.PreprocessUrl=e}}),Object.defineProperty(Ut,"CorsBehavior",{get:function(){return i.CorsBehavior},set:function(e){i.CorsBehavior=e}})})(Ft,wt,Mt,Pt,Nt,Ot,bt,yt,Dt,xt);class Bt{static Instantiate(e){if(this.RegisteredExternalClasses&&this.RegisteredExternalClasses[e])return this.RegisteredExternalClasses[e];const t=x(e);if(t)return t;de.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<t;e++)n=n[i[e]];return"function"!=typeof n?null:n}}function Gt(){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)}))}function Vt(e){let t=1;do{t*=2}while(t<e);return t===e}function kt(e,t,i){return e*(1-i)+t*i}function Xt(e){const t=Ht(e),i=Wt(e);return t-e>e-i?i:t}function Ht(e){return e--,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,++e}function Wt(e){return e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,(e|=e>>16)-(e>>1)}function zt(e,t,i=Ze.SCALEMODE_NEAREST){let n;switch(i){case Ze.SCALEMODE_FLOOR:n=Wt(e);break;case Ze.SCALEMODE_NEAREST:n=Xt(e);break;case Ze.SCALEMODE_CEILING:default:n=Ht(e)}return Math.min(n,t)}Bt.RegisteredExternalClasses={};class Yt{static get BaseUrl(){return Mt.BaseUrl}static set BaseUrl(e){Mt.BaseUrl=e}static get CleanUrl(){return Mt.CleanUrl}static set CleanUrl(e){Mt.CleanUrl=e}static IsAbsoluteUrl(e){return 0===e.indexOf("//")||-1!==e.indexOf("://")&&(-1!==e.indexOf(".")&&(-1!==e.indexOf("/")&&(!(e.indexOf(":")>e.indexOf("/"))&&(e.indexOf("://")<e.indexOf(".")||(0===e.indexOf("data:")||0===e.indexOf("blob:"))))))}static set ScriptBaseUrl(e){Mt.ScriptBaseUrl=e}static get ScriptBaseUrl(){return Mt.ScriptBaseUrl}static set ScriptPreprocessUrl(e){Mt.ScriptPreprocessUrl=e}static get ScriptPreprocessUrl(){return Mt.ScriptPreprocessUrl}static get DefaultRetryStrategy(){return Mt.DefaultRetryStrategy}static set DefaultRetryStrategy(e){Mt.DefaultRetryStrategy=e}static get CorsBehavior(){return Mt.CorsBehavior}static set CorsBehavior(e){Mt.CorsBehavior=e}static get UseFallbackTexture(){return y.UseFallbackTexture}static set UseFallbackTexture(e){y.UseFallbackTexture=e}static get RegisteredExternalClasses(){return Bt.RegisteredExternalClasses}static set RegisteredExternalClasses(e){Bt.RegisteredExternalClasses=e}static get fallbackTexture(){return y.FallbackTexture}static set fallbackTexture(e){y.FallbackTexture=e}static FetchToRef(e,t,i,n,r,s){const a=4*((Math.abs(e)*i%i|0)+(Math.abs(t)*n%n|0)*i);s.r=r[a]/255,s.g=r[a+1]/255,s.b=r[a+2]/255,s.a=r[a+3]/255}static Mix(e,t,i){return 0}static Instantiate(e){return Bt.Instantiate(e)}static SetImmediate(e){Qe.SetImmediate(e)}static IsExponentOfTwo(e){return!0}static FloatRound(e){return Math.fround(e)}static GetFilename(e){const t=e.lastIndexOf("/");return t<0?e:e.substring(t+1)}static GetFolderPath(e,t=!1){const i=e.lastIndexOf("/");return i<0?t?e:"":e.substring(0,i+1)}static ToDegrees(e){return 180*e/Math.PI}static ToRadians(e){return e*Math.PI/180}static SmoothAngleChange(e,t,i=.9){const n=this.ToRadians(e),r=this.ToRadians(t);return this.ToDegrees(Math.atan2((1-i)*Math.sin(r)+i*Math.sin(n),(1-i)*Math.cos(r)+i*Math.cos(n)))}static MakeArray(e,t){return!0===t||void 0!==e&&null!=e?Array.isArray(e)?e:[e]:null}static GetPointerPrefix(e){let t="pointer";return oe()&&!window.PointerEvent&&(t="mouse"),!e._badDesktopOS||e._badOS||document&&"ontouchend"in document||(t="mouse"),t}static SetCorsBehavior(e,t){xt(e,t)}static SetReferrerPolicyBehavior(e,t){t.referrerPolicy=e}static get PreprocessUrl(){return Mt.PreprocessUrl}static set PreprocessUrl(e){Mt.PreprocessUrl=e}static LoadImage(e,t,i,n,r,s){return bt(e,t,i,n,r,s)}static LoadFile(e,t,i,n,r,s){return Ot(e,t,i,n,r,s)}static LoadFileAsync(e,t=!0){return new Promise(((i,n)=>{Ot(e,(e=>{i(e)}),void 0,void 0,t,((e,t)=>{n(t)}))}))}static GetBabylonScriptURL(e,t){if(!e)return"";if(Yt.ScriptBaseUrl&&e.startsWith(Yt._DefaultCdnUrl)){const t="/"===Yt.ScriptBaseUrl[Yt.ScriptBaseUrl.length-1]?Yt.ScriptBaseUrl.substring(0,Yt.ScriptBaseUrl.length-1):Yt.ScriptBaseUrl;e=e.replace(Yt._DefaultCdnUrl,t)}return e=Yt.ScriptPreprocessUrl(e),t&&(e=Yt.GetAbsoluteUrl(e)),e}static LoadBabylonScript(e,t,i,n){e=Yt.GetBabylonScriptURL(e),Yt.LoadScript(e,t,i)}static LoadBabylonScriptAsync(e){return e=Yt.GetBabylonScriptURL(e),Yt.LoadScriptAsync(e)}static LoadScript(e,t,i,n){if("function"==typeof importScripts){try{importScripts(e),t()}catch(t){i?.(`Unable to load script '${e}' in worker`,t)}return}if(!oe())return void i?.(`Cannot load script '${e}' outside of a window or a worker`);const r=document.getElementsByTagName("head")[0],s=document.createElement("script");s.setAttribute("type","text/javascript"),s.setAttribute("src",e),n&&(s.id=n),s.onload=()=>{t&&t()},s.onerror=t=>{i&&i(`Unable to load script '${e}'`,t)},r.appendChild(s)}static LoadScriptAsync(e,t){return new Promise(((i,n)=>{this.LoadScript(e,(()=>{i()}),((e,t)=>{n(t||new Error(e))}),t)}))}static ReadFileAsDataURL(e,t,i){const n=new FileReader,r={onCompleteObservable:new g,abort:()=>n.abort()};return n.onloadend=()=>{r.onCompleteObservable.notifyObservers(r)},n.onload=e=>{t(e.target.result)},n.onprogress=i,n.readAsDataURL(e),r}static ReadFile(e,t,i,n,r){return yt(e,t,i,n,r)}static FileAsURL(e){const t=new Blob([e]);return window.URL.createObjectURL(t)}static Format(e,t=2){return e.toFixed(t)}static DeepCopy(e,t,i,n){fe.DeepCopy(e,t,i,n)}static IsEmpty(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}static RegisterTopRootEvents(e,t){for(let i=0;i<t.length;i++){const n=t[i];e.addEventListener(n.name,n.handler,!1);try{window.parent&&window.parent.addEventListener(n.name,n.handler,!1)}catch(e){}}}static UnregisterTopRootEvents(e,t){for(let i=0;i<t.length;i++){const n=t[i];e.removeEventListener(n.name,n.handler);try{e.parent&&e.parent.removeEventListener(n.name,n.handler)}catch(e){}}}static async DumpFramebuffer(e,t,i,n,r="image/png",s,a){throw Y("DumpTools")}static DumpData(e,t,i,n,r="image/png",s,a=!1,o=!1,l){throw Y("DumpTools")}static DumpDataAsync(e,t,i,n="image/png",r,s=!1,a=!1,o){throw Y("DumpTools")}static _IsOffScreenCanvas(e){return void 0!==e.convertToBlob}static ToBlob(e,t,i="image/png",n){Yt._IsOffScreenCanvas(e)||e.toBlob||(e.toBlob=function(e,t,i){setTimeout((()=>{const n=atob(this.toDataURL(t,i).split(",")[1]),r=n.length,s=new Uint8Array(r);for(let e=0;e<r;e++)s[e]=n.charCodeAt(e);e(new Blob([s]))}))}),Yt._IsOffScreenCanvas(e)?e.convertToBlob({type:i,quality:n}).then((e=>t(e))):e.toBlob((function(e){t(e)}),i,n)}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"}Yt.Download(e,t)}else if(e&&"undefined"!=typeof URL){const t=URL.createObjectURL(e),i=window.open("");if(!i)return;const n=i.document.createElement("img");n.onload=function(){URL.revokeObjectURL(t)},n.src=t,i.document.body.appendChild(n)}}static EncodeScreenshotCanvasData(e,t,i="image/png",n,r){if("string"!=typeof n&&t){if(t){if(Yt._IsOffScreenCanvas(e))return void e.convertToBlob({type:i,quality:r}).then((e=>{const i=new FileReader;i.readAsDataURL(e),i.onloadend=()=>{const e=i.result;t(e)}}));const n=e.toDataURL(i,r);t(n)}}else this.ToBlob(e,(function(e){e&&Yt.DownloadBlob(e,n),t&&t("")}),i,r)}static Download(e,t){if("undefined"==typeof URL)return;const i=window.URL.createObjectURL(e),n=document.createElement("a");document.body.appendChild(n),n.style.display="none",n.href=i,n.download=t,n.addEventListener("click",(()=>{n.parentElement&&n.parentElement.removeChild(n)})),n.click(),window.URL.revokeObjectURL(i)}static BackCompatCameraNoPreventDefault(e){return"boolean"==typeof e[0]?e[0]:"boolean"==typeof e[1]&&e[1]}static CreateScreenshot(e,t,i,n,r="image/png",s=!1,a){throw Y("ScreenshotTools")}static CreateScreenshotAsync(e,t,i,n="image/png",r){throw Y("ScreenshotTools")}static CreateScreenshotUsingRenderTarget(e,t,i,n,r="image/png",s=1,a=!1,o,l=!1,c=!1,h=!0,d){throw Y("ScreenshotTools")}static CreateScreenshotUsingRenderTargetAsync(e,t,i,n="image/png",r=1,s=!1,a,o=!1,l=!1,c=!0,h){throw Y("ScreenshotTools")}static RandomId(){return Gt()}static IsBase64(e){return Pt(e)}static DecodeBase64(e){return Ft(e)}static get errorsCount(){return de.errorsCount}static Log(e){de.Log(e)}static Warn(e){de.Warn(e)}static Error(e){de.Error(e)}static get LogCache(){return de.LogCache}static ClearLogCache(){de.ClearLogCache()}static set LogLevels(e){de.LogLevels=e}static set PerformanceLogLevel(e){return(e&Yt.PerformanceUserMarkLogLevel)===Yt.PerformanceUserMarkLogLevel?(Yt.StartPerformanceCounter=Yt._StartUserMark,void(Yt.EndPerformanceCounter=Yt._EndUserMark)):(e&Yt.PerformanceConsoleLogLevel)===Yt.PerformanceConsoleLogLevel?(Yt.StartPerformanceCounter=Yt._StartPerformanceConsole,void(Yt.EndPerformanceCounter=Yt._EndPerformanceConsole)):(Yt.StartPerformanceCounter=Yt._StartPerformanceCounterDisabled,void(Yt.EndPerformanceCounter=Yt._EndPerformanceCounterDisabled))}static _StartPerformanceCounterDisabled(e,t){}static _EndPerformanceCounterDisabled(e,t){}static _StartUserMark(e,t=!0){if(!Yt._Performance){if(!oe())return;Yt._Performance=window.performance}t&&Yt._Performance.mark&&Yt._Performance.mark(e+"-Begin")}static _EndUserMark(e,t=!0){t&&Yt._Performance.mark&&(Yt._Performance.mark(e+"-End"),Yt._Performance.measure(e,e+"-Begin",e+"-End"))}static _StartPerformanceConsole(e,t=!0){t&&(Yt._StartUserMark(e,t),console.time&&console.time(e))}static _EndPerformanceConsole(e,t=!0){t&&(Yt._EndUserMark(e,t),console.timeEnd(e))}static get Now(){return _e.Now}static GetClassName(e,t=!1){let i=null;if(!t&&e.getClassName)i=e.getClassName();else{if(e instanceof Object){i=(t?e:Object.getPrototypeOf(e)).constructor.__bjsclassName__}i||(i=typeof e)}return i}static First(e,t){for(const i of e)if(t(i))return i;return null}static getFullClassName(e,t=!1){let i=null,n=null;if(!t&&e.getClassName)i=e.getClassName();else{if(e instanceof Object){const r=t?e:Object.getPrototypeOf(e);i=r.constructor.__bjsclassName__,n=r.constructor.__bjsmoduleName__}i||(i=typeof e)}return i?(null!=n?n+".":"")+i:null}static DelayAsync(e){return new Promise((t=>{setTimeout((()=>{t()}),e)}))}static IsSafari(){return!!le()&&/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}}Yt.UseCustomRequestHeaders=!1,Yt.CustomRequestHeaders=me.CustomRequestHeaders,Yt.GetDOMTextContent=he,Yt._DefaultCdnUrl="https://cdn.babylonjs.com",Yt.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.")},Yt.NoneLogLevel=de.NoneLogLevel,Yt.MessageLogLevel=de.MessageLogLevel,Yt.WarningLogLevel=de.WarningLogLevel,Yt.ErrorLogLevel=de.ErrorLogLevel,Yt.AllLogLevel=de.AllLogLevel,Yt.IsWindowObjectExist=oe,Yt.PerformanceNoneLogLevel=0,Yt.PerformanceUserMarkLogLevel=1,Yt.PerformanceConsoleLogLevel=2,Yt.StartPerformanceCounter=Yt._StartPerformanceCounterDisabled,Yt.EndPerformanceCounter=Yt._EndPerformanceCounterDisabled;class Kt{constructor(e,t,i,n=0){this.iterations=e,this.index=n-1,this._done=!1,this._fn=t,this._successCallback=i}executeNext(){this._done||(this.index+1<this.iterations?(++this.index,this._fn(this)):this.breakLoop())}breakLoop(){this._done=!0,this._successCallback()}static Run(e,t,i,n=0){const r=new Kt(e,t,i,n);return r.executeNext(),r}static SyncAsyncForLoop(e,t,i,n,r,s=0){return Kt.Run(Math.ceil(e/t),(n=>{r&&r()?n.breakLoop():setTimeout((()=>{for(let s=0;s<t;++s){const a=n.index*t+s;if(a>=e)break;if(i(a),r&&r()){n.breakLoop();break}}n.executeNext()}),s)}),n)}}function qt(e,t,i){try{const n=e.next();n.done?t(n):n.value?n.value.then((()=>{n.value=void 0,t(n)}),i):t(n)}catch(e){i(e)}}function jt(e,t,i,n,r){const s=()=>{let r;const a=e=>{e.done?i(e.value):void 0===r?r=!0:s()};do{r=void 0,t(e,a,n),void 0===r&&(r=!1)}while(r)};s()}function Qt(e,t){let i;return jt(e,qt,(e=>i=e),(e=>{throw e})),i}Yt.Mix=kt,Yt.IsExponentOfTwo=Vt,y.FallbackTexture="data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";class Zt{constructor(e){this.length=0,this.data=new Array(e),this._id=Zt._GlobalId++}push(e){this.data[this.length++]=e,this.length>this.data.length&&(this.data.length*=2)}forEach(e){for(let t=0;t<this.length;t++)e(this.data[t])}sort(e){this.data.sort(e)}reset(){this.length=0}dispose(){this.reset(),this.data&&(this.data.length=0)}concat(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<e.length;t++)this.data[this.length++]=(e.data||e)[t]}}indexOf(e){const t=this.data.indexOf(e);return t>=this.length?-1:t}contains(e){return-1!==this.indexOf(e)}}Zt._GlobalId=0;class Jt extends Zt{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<e.length;t++){const i=(e.data||e)[t];this.pushNoDuplicate(i)}}}}class $t{constructor(e,t,i,n){this.x=e,this.y=t,this.width=i,this.height=n}toGlobal(e,t){return new $t(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 $t(this.x,this.y,this.width,this.height)}}class ei{constructor(e,t,i,n){this.normal=new B(e,t,i),this.d=n}asArray(){return[this.normal.x,this.normal.y,this.normal.z,this.d]}clone(){return new ei(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=ei._TmpMatrix;e.invertToRef(t);const i=t.m,n=this.normal.x,r=this.normal.y,s=this.normal.z,a=this.d,o=n*i[0]+r*i[1]+s*i[2]+a*i[3],l=n*i[4]+r*i[5]+s*i[6]+a*i[7],c=n*i[8]+r*i[9]+s*i[10]+a*i[11],h=n*i[12]+r*i[13]+s*i[14]+a*i[15];return new ei(o,l,c,h)}dotCoordinate(e){return this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z+this.d}copyFromPoints(e,t,i){const n=t.x-e.x,r=t.y-e.y,s=t.z-e.z,a=i.x-e.x,o=i.y-e.y,l=i.z-e.z,c=r*l-s*o,h=s*a-n*l,d=n*o-r*a,u=Math.sqrt(c*c+h*h+d*d);let f;return f=0!==u?1/u:0,this.normal.x=c*f,this.normal.y=h*f,this.normal.z=d*f,this.d=-(this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z),this}isFrontFacingTo(e,t){return B.Dot(this.normal,e)<=t}signedDistanceTo(e){return B.Dot(e,this.normal)+this.d}static FromArray(e){return new ei(e[0],e[1],e[2],e[3])}static FromPoints(e,t,i){const n=new ei(0,0,0,0);return n.copyFromPoints(e,t,i),n}static FromPositionAndNormal(e,t){const i=new ei(0,0,0,0);return this.FromPositionAndNormalToRef(e,t,i)}static FromPositionAndNormalToRef(e,t,i){return i.normal.copyFrom(t),i.normal.normalize(),i.d=-e.dot(i.normal),i}static SignedDistanceToPlaneFromPositionAndNormal(e,t,i){const n=-(t.x*e.x+t.y*e.y+t.z*e.z);return B.Dot(i,t)+n}}ei._TmpMatrix=k.Identity();class ti{static GetPlanes(e){const t=[];for(let e=0;e<6;e++)t.push(new ei(0,0,0,0));return ti.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){ti.GetNearPlaneToRef(e,t[0]),ti.GetFarPlaneToRef(e,t[1]),ti.GetLeftPlaneToRef(e,t[2]),ti.GetRightPlaneToRef(e,t[3]),ti.GetTopPlaneToRef(e,t[4]),ti.GetBottomPlaneToRef(e,t[5])}static IsPointInFrustum(e,t){for(let i=0;i<6;i++)if(t[i].dotCoordinate(e)<0)return!1;return!0}}class ii extends ae{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===ii.PERSPECTIVE_CAMERA)this.fovMode===ii.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,n=this.getEngine().getRenderHeight()/2;e=(this.orthoRight??i)-(this.orthoLeft??-i),t=(this.orthoTop??n)-(this.orthoBottom??-n)}return e*t}set orthoLeft(e){this._orthoLeft=e;for(const t of this._rigCameras)t.orthoLeft=e}get orthoLeft(){return this._orthoLeft}set orthoRight(e){this._orthoRight=e;for(const t of this._rigCameras)t.orthoRight=e}get orthoRight(){return this._orthoRight}set orthoBottom(e){this._orthoBottom=e;for(const t of this._rigCameras)t.orthoBottom=e}get orthoBottom(){return this._orthoBottom}set orthoTop(e){this._orthoTop=e;for(const t of this._rigCameras)t.orthoTop=e}get orthoTop(){return this._orthoTop}set mode(e){this._mode=e;for(const t of this._rigCameras)t.mode=e}get mode(){return this._mode}get hasMoved(){return this._hasMoved}constructor(e,t,i,n=!0){super(e,i,!1),this._position=B.Zero(),this._upVector=B.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=ii.PERSPECTIVE_CAMERA,this.isIntermediate=!1,this.viewport=new $t(0,0,1,1),this.layerMask=268435455,this.fovMode=ii.FOVMODE_VERTICAL_FIXED,this.cameraRigMode=ii.RIG_MODE_NONE,this.customRenderTargets=[],this.outputRenderTarget=null,this.onViewMatrixChangedObservable=new g,this.onProjectionMatrixChangedObservable=new g,this.onAfterCheckInputsObservable=new g,this.onRestoreStateObservable=new g,this.isRigCamera=!1,this._hasMoved=!1,this._rigCameras=new Array,this._skipRendering=!1,this._projectionMatrix=new k,this._postProcesses=new Array,this._activeMeshes=new Zt(256),this._globalPosition=B.Zero(),this._computedViewMatrix=k.Identity(),this._doNotComputeProjectionMatrix=!1,this._transformMatrix=k.Zero(),this._refreshFrustumPlanes=!0,this._absoluteRotation=V.Identity(),this._isCamera=!0,this._isLeftCamera=!1,this._isRightCamera=!1,this.getScene().addCamera(this),n&&!this.getScene().activeCamera&&(this.getScene().activeCamera=this),this.position=t,this.renderPassId=this.getScene().getEngine().createRenderPassId(`Camera ${e}`)}storeState(){return this._stateStored=!0,this._storedFov=this.fov,this}hasStateStored(){return!!this._stateStored}_restoreStateValues(){return!!this._stateStored&&(this.fov=this._storedFov,!0)}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<this.animations.length;i++)t+=", animation[0]: "+this.animations[i].toString(e);return t}applyVerticalCorrection(){const e=this.absoluteRotation.toEulerAngles();this.projectionPlaneTilt=this._scene.useRightHandedSystem?-e.x:e.x}get globalPosition(){return this._globalPosition}getActiveMeshes(){return this._activeMeshes}isActiveMesh(e){return-1!==this._activeMeshes.indexOf(e)}isReady(e=!1){if(e)for(const e of this._postProcesses)if(e&&!e.isReady())return!1;return super.isReady(e)}_initCache(){super._initCache(),this._cache.position=new B(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.upVector=new B(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.mode=void 0,this._cache.minZ=void 0,this._cache.maxZ=void 0,this._cache.fov=void 0,this._cache.fovMode=void 0,this._cache.aspectRatio=void 0,this._cache.orthoLeft=void 0,this._cache.orthoRight=void 0,this._cache.orthoBottom=void 0,this._cache.orthoTop=void 0,this._cache.obliqueAngle=void 0,this._cache.obliqueLength=void 0,this._cache.obliqueOffset=void 0,this._cache.renderWidth=void 0,this._cache.renderHeight=void 0}_updateCache(e){e||super._updateCache(),this._cache.position.copyFrom(this.position),this._cache.upVector.copyFrom(this.upVector)}_isSynchronized(){return this._isSynchronizedViewMatrix()&&this._isSynchronizedProjectionMatrix()}_isSynchronizedViewMatrix(){return!!super._isSynchronized()&&(this._cache.position.equals(this.position)&&this._cache.upVector.equals(this.upVector)&&this.isSynchronizedWithParent())}_isSynchronizedProjectionMatrix(){let e=this._cache.mode===this.mode&&this._cache.minZ===this.minZ&&this._cache.maxZ===this.maxZ;if(!e)return!1;const t=this.getEngine();return this.mode===ii.PERSPECTIVE_CAMERA?e=this._cache.fov===this.fov&&this._cache.fovMode===this.fovMode&&this._cache.aspectRatio===t.getAspectRatio(this)&&this._cache.projectionPlaneTilt===this.projectionPlaneTilt:(e=this._cache.orthoLeft===this.orthoLeft&&this._cache.orthoRight===this.orthoRight&&this._cache.orthoBottom===this.orthoBottom&&this._cache.orthoTop===this.orthoTop&&this._cache.renderWidth===t.getRenderWidth()&&this._cache.renderHeight===t.getRenderHeight(),this.oblique&&(e=e&&this._cache.obliqueAngle===this.oblique.angle&&this._cache.obliqueLength===this.oblique.length&&this._cache.obliqueOffset===this.oblique.offset)),e}attachControl(e,t){}detachControl(e){}update(){this._hasMoved=!1,this._checkInputs(),this.cameraRigMode!==ii.RIG_MODE_NONE&&this._updateRigCameras(),this.getViewMatrix(),this.getProjectionMatrix()}_checkInputs(){this.onAfterCheckInputsObservable.notifyObservers(this)}get rigCameras(){return this._rigCameras}get rigPostProcess(){return this._rigPostProcess}_getFirstPostProcess(){for(let e=0;e<this._postProcesses.length;e++)if(null!==this._postProcesses[e])return this._postProcesses[e];return null}_cascadePostProcessesToRigCams(){const e=this._getFirstPostProcess();e&&e.markTextureDirty();for(let e=0,t=this._rigCameras.length;e<t;e++){const t=this._rigCameras[e],i=t._rigPostProcess;if(i){"pass"===i.getEffectName()&&(t.isIntermediate=0===this._postProcesses.length),t._postProcesses=this._postProcesses.slice(0).concat(i),i.markTextureDirty()}else t._postProcesses=this._postProcesses.slice(0)}}attachPostProcess(e,t=null){return!e.isReusable()&&this._postProcesses.indexOf(e)>-1?(de.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 k.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(),n=t.useReverseDepthBuffer;if(this.mode===ii.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?k.PerspectiveFovRHToRef:k.PerspectiveFovLHToRef,e(this.fov,t.getAspectRatio(this),n?this.maxZ:this.minZ,n?this.minZ:this.maxZ,this._projectionMatrix,this.fovMode===ii.FOVMODE_VERTICAL_FIXED,t.isNDCHalfZRange,this.projectionPlaneTilt,n)}else{const e=t.getRenderWidth()/2,r=t.getRenderHeight()/2;i.useRightHandedSystem?this.oblique?k.ObliqueOffCenterRHToRef(this.orthoLeft??-e,this.orthoRight??e,this.orthoBottom??-r,this.orthoTop??r,n?this.maxZ:this.minZ,n?this.minZ:this.maxZ,this.oblique.length,this.oblique.angle,this._computeObliqueDistance(this.oblique.offset),this._projectionMatrix,t.isNDCHalfZRange):k.OrthoOffCenterRHToRef(this.orthoLeft??-e,this.orthoRight??e,this.orthoBottom??-r,this.orthoTop??r,n?this.maxZ:this.minZ,n?this.minZ:this.maxZ,this._projectionMatrix,t.isNDCHalfZRange):this.oblique?k.ObliqueOffCenterLHToRef(this.orthoLeft??-e,this.orthoRight??e,this.orthoBottom??-r,this.orthoTop??r,n?this.maxZ:this.minZ,n?this.minZ:this.maxZ,this.oblique.length,this.oblique.angle,this._computeObliqueDistance(this.oblique.offset),this._projectionMatrix,t.isNDCHalfZRange):k.OrthoOffCenterLHToRef(this.orthoLeft??-e,this.orthoRight??e,this.orthoBottom??-r,this.orthoTop??r,n?this.maxZ:this.minZ,n?this.minZ:this.maxZ,this._projectionMatrix,t.isNDCHalfZRange),this._cache.orthoLeft=this.orthoLeft,this._cache.orthoRight=this.orthoRight,this._cache.orthoBottom=this.orthoBottom,this._cache.orthoTop=this.orthoTop,this._cache.obliqueAngle=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?B.Distance(this.position,this.target):this.position.length()))+e}_updateFrustumPlanes(){this._refreshFrustumPlanes&&(this.getTransformationMatrix(),this._frustumPlanes?ti.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=ti.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 Y("Ray")}getForwardRayToRef(e,t=100,i,n){throw Y("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!==ii.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=Yt.ToRadians(this._cameraRigParams.interaxialDistance/.0637),this.cameraRigMode!==ii.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 k.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=Yt.ToRadians(t/.0637))}createRigCamera(e,t){return null}_updateRigCameras(){for(let e=0;e<this._rigCameras.length;e++)this._rigCameras[e].minZ=this.minZ,this._rigCameras[e].maxZ=this.maxZ,this._rigCameras[e].fov=this.fov,this._rigCameras[e].upVector.copyFrom(this.upVector);this.cameraRigMode===ii.RIG_MODE_STEREOSCOPIC_ANAGLYPH&&(this._rigCameras[0].viewport=this._rigCameras[1].viewport=this.viewport)}_setupInputs(){}serialize(){const e=re.Serialize(this);return e.uniqueId=this.uniqueId,e.type=this.getClassName(),this.parent&&this.parent._serializeAsParent(e),this.inputs&&this.inputs.serialize(e),re.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.isEnabled=this.isEnabled(),e}clone(e,t=null){const i=re.Clone(ii.GetConstructorFromName(this.getClassName(),e,this.getScene(),this.interaxialDistance,this.isStereoscopicSideBySide),this);return i.name=e,i.parent=t,this.onClonedObservable.notifyObservers(i),i}getDirection(e){const t=B.Zero();return this.getDirectionToRef(e,t),t}get absoluteRotation(){return this.getWorldMatrix().decompose(void 0,this._absoluteRotation),this._absoluteRotation}getDirectionToRef(e,t){B.TransformNormalToRef(e,this.getWorldMatrix(),t)}static GetConstructorFromName(e,t,i,n=0,r=!0){const s=ae.Construct(e,t,i,{interaxial_distance:n,isStereoscopicSideBySide:r});return s||(()=>ii._CreateDefaultParsedCamera(t,i))}computeWorldMatrix(){return this.getWorldMatrix()}static Parse(e,t){const i=e.type,n=ii.GetConstructorFromName(i,e.name,t,e.interaxial_distance,e.isStereoscopicSideBySide),r=re.Parse(n,e,t);if(void 0!==e.parentId&&(r._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(r._waitingParentInstanceIndex=e.parentInstanceIndex),r.inputs&&(r.inputs.parse(e),r._setupInputs()),e.upVector&&(r.upVector=B.FromArray(e.upVector)),r.setPosition&&(r.position.copyFromFloats(0,0,0),r.setPosition(B.FromArray(e.position))),e.target&&r.setTarget&&r.setTarget(B.FromArray(e.target)),e.cameraRigMode){const t=e.interaxial_distance?{interaxialDistance:e.interaxial_distance}:{};r.setCameraRigMode(e.cameraRigMode,t)}if(e.animations){for(let t=0;t<e.animations.length;t++){const i=e.animations[t],n=x("BABYLON.Animation");n&&r.animations.push(n.Parse(i))}ae.ParseAnimationRanges(r,e,t)}return e.autoAnimate&&t.beginAnimation(r,e.autoAnimateFrom,e.autoAnimateTo,e.autoAnimateLoop,e.autoAnimateSpeed||1),void 0!==e.isEnabled&&r.setEnabled(e.isEnabled),r}_calculateHandednessMultiplier(){let e=this.getScene().useRightHandedSystem?-1:1;return this.parent&&this.parent._getWorldMatrixDeterminant()<0&&(e*=-1),e}}ii._CreateDefaultParsedCamera=(e,t)=>{throw Y("UniversalCamera")},ii.PERSPECTIVE_CAMERA=Ze.PERSPECTIVE_CAMERA,ii.ORTHOGRAPHIC_CAMERA=Ze.ORTHOGRAPHIC_CAMERA,ii.FOVMODE_VERTICAL_FIXED=Ze.FOVMODE_VERTICAL_FIXED,ii.FOVMODE_HORIZONTAL_FIXED=Ze.FOVMODE_HORIZONTAL_FIXED,ii.RIG_MODE_NONE=Ze.RIG_MODE_NONE,ii.RIG_MODE_STEREOSCOPIC_ANAGLYPH=Ze.RIG_MODE_STEREOSCOPIC_ANAGLYPH,ii.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=Ze.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL,ii.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=Ze.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED,ii.RIG_MODE_STEREOSCOPIC_OVERUNDER=Ze.RIG_MODE_STEREOSCOPIC_OVERUNDER,ii.RIG_MODE_STEREOSCOPIC_INTERLACED=Ze.RIG_MODE_STEREOSCOPIC_INTERLACED,ii.RIG_MODE_VR=Ze.RIG_MODE_VR,ii.RIG_MODE_CUSTOM=Ze.RIG_MODE_CUSTOM,ii.ForceAttachControlToAlwaysPreventDefault=!1,e([h("position")],ii.prototype,"_position",void 0),e([h("upVector")],ii.prototype,"_upVector",void 0),e([a()],ii.prototype,"orthoLeft",null),e([a()],ii.prototype,"orthoRight",null),e([a()],ii.prototype,"orthoBottom",null),e([a()],ii.prototype,"orthoTop",null),e([a()],ii.prototype,"fov",void 0),e([a()],ii.prototype,"projectionPlaneTilt",void 0),e([a()],ii.prototype,"minZ",void 0),e([a()],ii.prototype,"maxZ",void 0),e([a()],ii.prototype,"inertia",void 0),e([a()],ii.prototype,"mode",null),e([a()],ii.prototype,"layerMask",void 0),e([a()],ii.prototype,"fovMode",void 0),e([a()],ii.prototype,"cameraRigMode",void 0),e([a()],ii.prototype,"interaxialDistance",void 0),e([a()],ii.prototype,"isStereoscopicSideBySide",void 0);class ni{get underlyingResource(){return null}constructor(){this.references=0,this.capacity=0,this.is32Bits=!1,this.uniqueId=ni._Counter++}}ni._Counter=0;class ri{get isDisposed(){return this._isDisposed}constructor(e,t,i,n=0,r=!1,s=!1,a=!1,o,l){this._isAlreadyOwned=!1,this._isDisposed=!1,e&&e.getScene?this._engine=e.getScene().getEngine():this._engine=e,this._updatable=i,this._instanced=s,this._divisor=o||1,this._label=l,t instanceof ni?(this._data=null,this._buffer=t):(this._data=t,this._buffer=null),this.byteStride=a?n:n*Float32Array.BYTES_PER_ELEMENT,r||this.create()}createVertexBuffer(e,t,i,n,r,s=!1,a){const o=s?t:t*Float32Array.BYTES_PER_ELEMENT,l=n?s?n:n*Float32Array.BYTES_PER_ELEMENT:this.byteStride;return new si(this._engine,this,e,this._updatable,!0,l,void 0===r?this._instanced:r,o,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));de.Warn(`Missing data for buffer "${this._label}" ${this._buffer?"(uniqueId: "+this._buffer.uniqueId+")":""}. Buffer reconstruction failed.`),this._buffer=null}}update(e){this.create(e)}updateDirectly(e,t,i,n=!1){this._buffer&&this._updatable&&(this._engine.updateDynamicVertexBuffer(this._buffer,e,n?t:t*Float32Array.BYTES_PER_ELEMENT,i?i*this.byteStride:void 0),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 si{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,n,r,s,a,o,l,c,h=!1,d=!1,u=1,f=!1){this._isDisposed=!1;let _=!1;if(this.engine=e,"object"==typeof n&&null!==n?(_=n.updatable??!1,r=n.postponeInternalCreation,s=n.stride,a=n.instanced,o=n.offset,l=n.size,c=n.type,h=n.normalized??!1,d=n.useBytes??!1,u=n.divisor??1,f=n.takeBufferOwnership??!1,this._label=n.label):_=!!n,t instanceof ri?(this._buffer=t,this._ownsBuffer=f):(this._buffer=new ri(e,t,_,s,r,a,d,u,this._label),this._ownsBuffer=!0),this.uniqueId=si._Counter++,this._kind=i,void 0===c){const e=this.getData();this.type=e?si.GetDataType(e):si.FLOAT}else this.type=c;const m=si.GetTypeByteLength(this.type);d?(this._size=l||(s?s/m:si.DeduceStride(i)),this.byteStride=s||this._buffer.byteStride||this._size*m,this.byteOffset=o||0):(this._size=l||s||si.DeduceStride(i),this.byteStride=s?s*m:this._buffer.byteStride||this._size*m,this.byteOffset=(o||0)*m),this.normalized=h,this._instanced=void 0!==a&&a,this._instanceDivisor=a?u: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?si.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/si.GetTypeByteLength(this.type)}getOffset(){return this.byteOffset/si.GetTypeByteLength(this.type)}getSize(e=!1){return e?this._size*si.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){si.ForEach(this._buffer.getData(),this.byteOffset,this.byteStride,this._size,this.type,e,this.normalized,t)}_alignBuffer(){}static DeduceStride(e){switch(e){case si.UVKind:case si.UV2Kind:case si.UV3Kind:case si.UV4Kind:case si.UV5Kind:case si.UV6Kind:return 2;case si.NormalKind:case si.PositionKind:return 3;case si.ColorKind:case si.ColorInstanceKind:case si.MatricesIndicesKind:case si.MatricesIndicesExtraKind:case si.MatricesWeightsKind:case si.MatricesWeightsExtraKind:case si.TangentKind:return 4;default:throw new Error("Invalid kind '"+e+"'")}}static GetDataType(e){return e instanceof Int8Array?si.BYTE:e instanceof Uint8Array?si.UNSIGNED_BYTE:e instanceof Int16Array?si.SHORT:e instanceof Uint16Array?si.UNSIGNED_SHORT:e instanceof Int32Array?si.INT:e instanceof Uint32Array?si.UNSIGNED_INT:si.FLOAT}static GetTypeByteLength(e){switch(e){case si.BYTE:case si.UNSIGNED_BYTE:return 1;case si.SHORT:case si.UNSIGNED_SHORT:return 2;case si.INT:case si.UNSIGNED_INT:case si.FLOAT:return 4;default:throw new Error(`Invalid type '${e}'`)}}static ForEach(e,t,i,n,r,s,a,o){if(e instanceof Array){let r=t/4;const a=i/4;for(let t=0;t<s;t+=n){for(let i=0;i<n;i++)o(e[r+i],t+i);r+=a}}else{const l=e instanceof ArrayBuffer?new DataView(e):new DataView(e.buffer,e.byteOffset,e.byteLength),c=si.GetTypeByteLength(r);for(let e=0;e<s;e+=n){let s=t;for(let t=0;t<n;t++){o(si._GetFloatValue(l,r,s,a),e+t),s+=c}t+=i}}}static _GetFloatValue(e,t,i,n){switch(t){case si.BYTE:{let t=e.getInt8(i);return n&&(t=Math.max(t/127,-1)),t}case si.UNSIGNED_BYTE:{let t=e.getUint8(i);return n&&(t/=255),t}case si.SHORT:{let t=e.getInt16(i,!0);return n&&(t=Math.max(t/32767,-1)),t}case si.UNSIGNED_SHORT:{let t=e.getUint16(i,!0);return n&&(t/=65535),t}case si.INT:return e.getInt32(i,!0);case si.UNSIGNED_INT:return e.getUint32(i,!0);case si.FLOAT:return e.getFloat32(i,!0);default:throw new Error(`Invalid component type ${t}`)}}static GetFloatData(e,t,i,n,r,s,a,o){const l=t*si.GetTypeByteLength(i),c=a*t;if(i!==si.FLOAT||r!==l){const a=new Float32Array(c);return si.ForEach(e,n,r,t,i,c,s,((e,t)=>a[t]=e)),a}if(!(e instanceof Array||e instanceof Float32Array)||0!==n||e.length!==c){if(e instanceof Array){const t=n/4;return e.slice(t,t+c)}if(e instanceof ArrayBuffer)return new Float32Array(e,n,c);{const t=e.byteOffset+n;if(3&t&&(de.Warn("Float array must be aligned to 4-bytes border"),o=!0),o){const i=new Uint8Array(c*Float32Array.BYTES_PER_ELEMENT),n=new Uint8Array(e.buffer,t,i.length);return i.set(n),new Float32Array(i.buffer)}return new Float32Array(e.buffer,t,c)}}return o?e.slice():e}}si._Counter=0,si.BYTE=Ze.BYTE,si.UNSIGNED_BYTE=Ze.UNSIGNED_BYTE,si.SHORT=Ze.SHORT,si.UNSIGNED_SHORT=Ze.UNSIGNED_SHORT,si.INT=Ze.INT,si.UNSIGNED_INT=Ze.UNSIGNED_INT,si.FLOAT=Ze.FLOAT,si.PositionKind=Ze.PositionKind,si.NormalKind=Ze.NormalKind,si.TangentKind=Ze.TangentKind,si.UVKind=Ze.UVKind,si.UV2Kind=Ze.UV2Kind,si.UV3Kind=Ze.UV3Kind,si.UV4Kind=Ze.UV4Kind,si.UV5Kind=Ze.UV5Kind,si.UV6Kind=Ze.UV6Kind,si.ColorKind=Ze.ColorKind,si.ColorInstanceKind=Ze.ColorInstanceKind,si.MatricesIndicesKind=Ze.MatricesIndicesKind,si.MatricesWeightsKind=Ze.MatricesWeightsKind,si.MatricesIndicesExtraKind=Ze.MatricesIndicesExtraKind,si.MatricesWeightsExtraKind=Ze.MatricesWeightsExtraKind;class ai{constructor(e,t,i){this.bu=e,this.bv=t,this.distance=i,this.faceId=0,this.subMeshId=0}}class oi{constructor(e,t,i){this.vectors=v(8,B.Zero),this.center=B.Zero(),this.centerWorld=B.Zero(),this.extendSize=B.Zero(),this.extendSizeWorld=B.Zero(),this.directions=v(3,B.Zero),this.vectorsWorld=v(8,B.Zero),this.minimumWorld=B.Zero(),this.maximumWorld=B.Zero(),this.minimum=B.Zero(),this.maximum=B.Zero(),this._drawWrapperFront=null,this._drawWrapperBack=null,this.reConstruct(e,t,i)}reConstruct(e,t,i){const n=e.x,r=e.y,s=e.z,a=t.x,o=t.y,l=t.z,c=this.vectors;this.minimum.copyFromFloats(n,r,s),this.maximum.copyFromFloats(a,o,l),c[0].copyFromFloats(n,r,s),c[1].copyFromFloats(a,o,l),c[2].copyFromFloats(a,r,s),c[3].copyFromFloats(n,o,s),c[4].copyFromFloats(n,r,l),c[5].copyFromFloats(a,o,s),c[6].copyFromFloats(n,o,l),c[7].copyFromFloats(a,r,l),t.addToRef(e,this.center).scaleInPlace(.5),t.subtractToRef(e,this.extendSize).scaleInPlace(.5),this._worldMatrix=i||k.IdentityReadOnly,this._update(this._worldMatrix)}scale(e){const t=oi._TmpVector3,i=this.maximum.subtractToRef(this.minimum,t[0]),n=i.length();i.normalizeFromLength(n);const r=n*e,s=i.scaleInPlace(.5*r),a=this.center.subtractToRef(s,t[1]),o=this.center.addToRef(s,t[2]);return this.reConstruct(a,o,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){const t=this.minimumWorld,i=this.maximumWorld,n=this.directions,r=this.vectorsWorld,s=this.vectors;if(e.isIdentity()){t.copyFrom(this.minimum),i.copyFrom(this.maximum);for(let e=0;e<8;++e)r[e].copyFrom(s[e]);this.extendSizeWorld.copyFrom(this.extendSize),this.centerWorld.copyFrom(this.center)}else{t.setAll(Number.MAX_VALUE),i.setAll(-Number.MAX_VALUE);for(let n=0;n<8;++n){const a=r[n];B.TransformCoordinatesToRef(s[n],e,a),t.minimizeInPlace(a),i.maximizeInPlace(a)}i.subtractToRef(t,this.extendSizeWorld).scaleInPlace(.5),i.addToRef(t,this.centerWorld).scaleInPlace(.5)}B.FromArrayToRef(e.m,0,n[0]),B.FromArrayToRef(e.m,4,n[1]),B.FromArrayToRef(e.m,8,n[2]),this._worldMatrix=e}isInFrustum(e){return oi.IsInFrustum(this.vectorsWorld,e)}isCompletelyInFrustum(e){return oi.IsCompletelyInFrustum(this.vectorsWorld,e)}intersectsPoint(e){const t=this.minimumWorld,i=this.maximumWorld,n=t.x,r=t.y,s=t.z,a=i.x,o=i.y,l=i.z,c=e.x,h=e.y,d=e.z,u=-A;return!(a-c<u||u>c-n)&&(!(o-h<u||u>h-r)&&!(l-d<u||u>d-s))}intersectsSphere(e){return oi.IntersectsSphere(this.minimumWorld,this.maximumWorld,e.centerWorld,e.radiusWorld)}intersectsMinMax(e,t){const i=this.minimumWorld,n=this.maximumWorld,r=i.x,s=i.y,a=i.z,o=n.x,l=n.y,c=n.z,h=e.x,d=e.y,u=e.z,f=t.x,_=t.y,m=t.z;return!(o<h||r>f)&&(!(l<d||s>_)&&!(c<u||a>m))}dispose(){this._drawWrapperFront?.dispose(),this._drawWrapperBack?.dispose()}static Intersects(e,t){return e.intersectsMinMax(t.minimumWorld,t.maximumWorld)}static IntersectsSphere(e,t,i,n){const r=oi._TmpVector3[0];B.ClampToRef(i,e,t,r);return B.DistanceSquared(i,r)<=n*n}static IsCompletelyInFrustum(e,t){for(let i=0;i<6;++i){const n=t[i];for(let t=0;t<8;++t)if(n.dotCoordinate(e[t])<0)return!1}return!0}static IsInFrustum(e,t){for(let i=0;i<6;++i){let n=!0;const r=t[i];for(let t=0;t<8;++t)if(r.dotCoordinate(e[t])>=0){n=!1;break}if(n)return!1}return!0}}oi._TmpVector3=v(3,B.Zero);class li{constructor(e,t,i){this.center=B.Zero(),this.centerWorld=B.Zero(),this.minimum=B.Zero(),this.maximum=B.Zero(),this.reConstruct(e,t,i)}reConstruct(e,t,i){this.minimum.copyFrom(e),this.maximum.copyFrom(t);const n=B.Distance(e,t);t.addToRef(e,this.center).scaleInPlace(.5),this.radius=.5*n,this._update(i||k.IdentityReadOnly)}scale(e){const t=this.radius*e,i=li._TmpVector3,n=i[0].setAll(t),r=this.center.subtractToRef(n,i[1]),s=this.center.addToRef(n,i[2]);return this.reConstruct(r,s,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){if(e.isIdentity())this.centerWorld.copyFrom(this.center),this.radiusWorld=this.radius;else{B.TransformCoordinatesToRef(this.center,e,this.centerWorld);const t=li._TmpVector3[0];B.TransformNormalFromFloatsToRef(1,1,1,e,t),this.radiusWorld=Math.max(Math.abs(t.x),Math.abs(t.y),Math.abs(t.z))*this.radius}}isInFrustum(e){const t=this.centerWorld,i=this.radiusWorld;for(let n=0;n<6;n++)if(e[n].dotCoordinate(t)<=-i)return!1;return!0}isCenterInFrustum(e){const t=this.centerWorld;for(let i=0;i<6;i++)if(e[i].dotCoordinate(t)<0)return!1;return!0}intersectsPoint(e){const t=B.DistanceSquared(this.centerWorld,e);return!(this.radiusWorld*this.radiusWorld<t)}static Intersects(e,t){const i=B.DistanceSquared(e.centerWorld,t.centerWorld),n=e.radiusWorld+t.radiusWorld;return!(n*n<i)}static CreateFromCenterAndRadius(e,t,i){this._TmpVector3[0].copyFrom(e),this._TmpVector3[1].copyFromFloats(0,0,t),this._TmpVector3[2].copyFrom(e),this._TmpVector3[0].addInPlace(this._TmpVector3[1]),this._TmpVector3[2].subtractInPlace(this._TmpVector3[1]);const n=new li(this._TmpVector3[0],this._TmpVector3[2]);return n._worldMatrix=i||k.Identity(),n}}li._TmpVector3=v(3,B.Zero);const ci={min:0,max:0},hi={min:0,max:0},di=(e,t,i)=>{const n=B.Dot(t.centerWorld,e),r=Math.abs(B.Dot(t.directions[0],e))*t.extendSize.x+Math.abs(B.Dot(t.directions[1],e))*t.extendSize.y+Math.abs(B.Dot(t.directions[2],e))*t.extendSize.z;i.min=n-r,i.max=n+r},ui=(e,t,i)=>(di(e,t,ci),di(e,i,hi),!(ci.min>hi.max||hi.min>ci.max));class fi{constructor(e,t,i){this._isLocked=!1,this.boundingBox=new oi(e,t,i),this.boundingSphere=new li(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=fi._TmpVector3[0].copyFrom(e).subtractInPlace(t),n=fi._TmpVector3[1].copyFrom(e).addInPlace(t);return this.boundingBox.reConstruct(i,n,this.boundingBox.getWorldMatrix()),this.boundingSphere.reConstruct(i,n,this.boundingBox.getWorldMatrix()),this}encapsulate(e){const t=B.Minimize(this.minimum,e),i=B.Maximize(this.maximum,e);return this.reConstruct(t,i,this.boundingBox.getWorldMatrix()),this}encapsulateBoundingInfo(e){const t=H.Matrix[0];this.boundingBox.getWorldMatrix().invertToRef(t);const i=H.Vector3[0];return B.TransformCoordinatesToRef(e.boundingBox.minimumWorld,t,i),this.encapsulate(i),B.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=Ze.MESHES_CULLINGSTRATEGY_STANDARD){if((t===Ze.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION||t===Ze.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY)&&this.boundingSphere.isCenterInFrustum(e))return!0;if(!this.boundingSphere.isInFrustum(e))return!1;return!(t!==Ze.MESHES_CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY&&t!==Ze.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY)||this.boundingBox.isInFrustum(e)}get diagonalLength(){const e=this.boundingBox;return e.maximumWorld.subtractToRef(e.minimumWorld,fi._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(!li.Intersects(this.boundingSphere,e.boundingSphere))return!1;if(!oi.Intersects(this.boundingBox,e.boundingBox))return!1;if(!t)return!0;const i=this.boundingBox,n=e.boundingBox;return!!ui(i.directions[0],i,n)&&(!!ui(i.directions[1],i,n)&&(!!ui(i.directions[2],i,n)&&(!!ui(n.directions[0],i,n)&&(!!ui(n.directions[1],i,n)&&(!!ui(n.directions[2],i,n)&&(!!ui(B.Cross(i.directions[0],n.directions[0]),i,n)&&(!!ui(B.Cross(i.directions[0],n.directions[1]),i,n)&&(!!ui(B.Cross(i.directions[0],n.directions[2]),i,n)&&(!!ui(B.Cross(i.directions[1],n.directions[0]),i,n)&&(!!ui(B.Cross(i.directions[1],n.directions[1]),i,n)&&(!!ui(B.Cross(i.directions[1],n.directions[2]),i,n)&&(!!ui(B.Cross(i.directions[2],n.directions[0]),i,n)&&(!!ui(B.Cross(i.directions[2],n.directions[1]),i,n)&&!!ui(B.Cross(i.directions[2],n.directions[2]),i,n))))))))))))))}}fi._TmpVector3=v(2,B.Zero);class _i{static extractMinAndMaxIndexed(e,t,i,n,r,s){for(let a=i;a<i+n;a++){const i=3*t[a],n=e[i],o=e[i+1],l=e[i+2];r.minimizeInPlaceFromFloats(n,o,l),s.maximizeInPlaceFromFloats(n,o,l)}}static extractMinAndMax(e,t,i,n,r,s){for(let a=t,o=t*n;a<t+i;a++,o+=n){const t=e[o],i=e[o+1],n=e[o+2];r.minimizeInPlaceFromFloats(t,i,n),s.maximizeInPlaceFromFloats(t,i,n)}}}function mi(e,t,i,n=null,r){const s=new B(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),a=new B(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);return r||(r=3),_i.extractMinAndMax(e,t,i,r,s,a),n&&(s.x-=s.x*n.x+n.y,s.y-=s.y*n.x+n.y,s.z-=s.z*n.x+n.y,a.x+=a.x*n.x+n.y,a.y+=a.y*n.x+n.y,a.z+=a.z*n.x+n.y),{minimum:s,maximum:a}}e([_.filter(((...[e,t])=>!Array.isArray(e)&&!Array.isArray(t)))],_i,"extractMinAndMaxIndexed",null),e([_.filter(((...[e])=>!Array.isArray(e)))],_i,"extractMinAndMax",null);class pi{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.drawContext?.dispose()}}class gi{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 pi(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,n=!0){const r=this._drawWrapper;r.setEffect(e,t,n),void 0!==i&&(r.materialContext=i),e||(r.defines=null,r.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,n,r,s,a,o=!0){return new gi(e,t,i,n,r,s,a,o)}constructor(e,t,i,n,r,s,a,o=!0,l=!0){this.materialIndex=e,this.verticesStart=t,this.verticesCount=i,this.indexStart=n,this.indexCount=r,this._mainDrawWrapperOverride=null,this._linesIndexCount=0,this._linesIndexBuffer=null,this._lastColliderWorldVertices=null,this._lastColliderTransformMatrix=null,this._wasDispatched=!1,this._renderId=0,this._alphaIndex=0,this._distanceToCamera=0,this._currentMaterial=null,this._mesh=s,this._renderingMesh=a||s,l&&s.subMeshes.push(this),this._engine=this._mesh.getScene().getEngine(),this.resetDrawCache(),this._trianglePlanes=[],this._id=s.subMeshes.length-1,o&&(this.refreshBoundingInfo(),s.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(){const e=this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:null;return e||this._renderingMesh}getMaterial(e=!0){const t=this._renderingMesh.getMaterialForRenderPass(this._engine.currentRenderPassId)??this._renderingMesh.material;if(!t)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(si.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=function(e,t,i,n,r=null){const s=new B(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),a=new B(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);return _i.extractMinAndMaxIndexed(e,t,i,n,s,a),r&&(s.x-=s.x*r.x+r.y,s.y-=s.y*r.x+r.y,s.z-=s.z*r.x+r.y,a.x+=a.x*r.x+r.y,a.y+=a.y*r.x+r.y,a.z+=a.z*r.x+r.y),{minimum:s,maximum:a}}(e,t,this.indexStart,this.indexCount,this._renderingMesh.geometry.boundingBias);return this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new fi(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;t<this.indexStart+this.indexCount;t+=3)i.push(e[t],e[t+1],e[t+1],e[t+2],e[t+2],e[t]);this._linesIndexBuffer=t.createIndexBuffer(i),this._linesIndexCount=i.length}return this._linesIndexBuffer}canIntersects(e){const t=this.getBoundingInfo();return!!t&&e.intersectsBox(t.boundingBox)}intersects(e,t,i,n,r){const s=this.getMaterial();if(!s)return null;let a=3,o=!1;switch(s.fillMode){case Ze.MATERIAL_PointListDrawMode:case Ze.MATERIAL_LineLoopDrawMode:case Ze.MATERIAL_LineStripDrawMode:case Ze.MATERIAL_TriangleFanDrawMode:return null;case Ze.MATERIAL_TriangleStripDrawMode:a=1,o=!0}return s.fillMode===Ze.MATERIAL_LineListDrawMode?i.length?this._intersectLines(e,t,i,this._mesh.intersectionThreshold,n):this._intersectUnIndexedLines(e,t,i,this._mesh.intersectionThreshold,n):!i.length&&this._mesh._unIndexed?this._intersectUnIndexedTriangles(e,t,i,n,r):this._intersectTriangles(e,t,i,a,o,n,r)}_intersectLines(e,t,i,n,r){let s=null;for(let a=this.indexStart;a<this.indexStart+this.indexCount;a+=2){const o=t[i[a]],l=t[i[a+1]],c=e.intersectionSegment(o,l,n);if(!(c<0)&&((r||!s||c<s.distance)&&(s=new ai(null,null,c),s.faceId=a/2,r)))break}return s}_intersectUnIndexedLines(e,t,i,n,r){let s=null;for(let i=this.verticesStart;i<this.verticesStart+this.verticesCount;i+=2){const a=t[i],o=t[i+1],l=e.intersectionSegment(a,o,n);if(!(l<0)&&((r||!s||l<s.distance)&&(s=new ai(null,null,l),s.faceId=i/2,r)))break}return s}_intersectTriangles(e,t,i,n,r,s,a){let o=null,l=-1;for(let c=this.indexStart;c<this.indexStart+this.indexCount-(3-n);c+=n){l++;const n=i[c],h=i[c+1],d=i[c+2];if(r&&4294967295===d){c+=2;continue}const u=t[n],f=t[h],_=t[d];if(!u||!f||!_)continue;if(a&&!a(u,f,_,e,n,h,d))continue;const m=e.intersectsTriangle(u,f,_);if(m){if(m.distance<0)continue;if((s||!o||m.distance<o.distance)&&(o=m,o.faceId=l,s))break}}return o}_intersectUnIndexedTriangles(e,t,i,n,r){let s=null;for(let i=this.verticesStart;i<this.verticesStart+this.verticesCount;i+=3){const a=t[i],o=t[i+1],l=t[i+2];if(r&&!r(a,o,l,e,-1,-1,-1))continue;const c=e.intersectsTriangle(a,o,l);if(c){if(c.distance<0)continue;if((n||!s||c.distance<s.distance)&&(s=c,s.faceId=i/3,n))break}}return s}_rebuild(){this._linesIndexBuffer&&(this._linesIndexBuffer=null)}clone(e,t){const i=new gi(this.materialIndex,this.verticesStart,this.verticesCount,this.indexStart,this.indexCount,e,t,!1);if(!this.IsGlobal){const e=this.getBoundingInfo();if(!e)return i;i._boundingInfo=new fi(e.minimum,e.maximum)}return i}dispose(){this._linesIndexBuffer&&(this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer),this._linesIndexBuffer=null);const e=this._mesh.subMeshes.indexOf(this);this._mesh.subMeshes.splice(e,1),this.resetDrawCache()}getClassName(){return"SubMesh"}static CreateFromIndices(e,t,i,n,r,s=!0){let a=Number.MAX_VALUE,o=-Number.MAX_VALUE;const l=(r||n).getIndices();for(let e=t;e<t+i;e++){const t=l[e];t<a&&(a=t),t>o&&(o=t)}return new gi(e,a,o-a+1,t,i,n,r,s)}}class Ei{}class Ti{constructor(){var e;this.uniqueId=0,this.metadata={},this._applyTo=(e=this._applyToCoroutine.bind(this),(...t)=>Qt(e(...t))),this.uniqueId=Ti._UniqueIDGenerator,Ti._UniqueIDGenerator++}set(e,t){switch(e.length||de.Warn(`Setting vertex data kind '${t}' with an empty array`),t){case si.PositionKind:this.positions=e;break;case si.NormalKind:this.normals=e;break;case si.TangentKind:this.tangents=e;break;case si.UVKind:this.uvs=e;break;case si.UV2Kind:this.uvs2=e;break;case si.UV3Kind:this.uvs3=e;break;case si.UV4Kind:this.uvs4=e;break;case si.UV5Kind:this.uvs5=e;break;case si.UV6Kind:this.uvs6=e;break;case si.ColorKind:this.colors=e;break;case si.MatricesIndicesKind:this.matricesIndices=e;break;case si.MatricesWeightsKind:this.matricesWeights=e;break;case si.MatricesIndicesExtraKind:this.matricesIndicesExtra=e;break;case si.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(si.PositionKind,this.positions,t),i&&(yield)),this.normals&&(e.setVerticesData(si.NormalKind,this.normals,t),i&&(yield)),this.tangents&&(e.setVerticesData(si.TangentKind,this.tangents,t),i&&(yield)),this.uvs&&(e.setVerticesData(si.UVKind,this.uvs,t),i&&(yield)),this.uvs2&&(e.setVerticesData(si.UV2Kind,this.uvs2,t),i&&(yield)),this.uvs3&&(e.setVerticesData(si.UV3Kind,this.uvs3,t),i&&(yield)),this.uvs4&&(e.setVerticesData(si.UV4Kind,this.uvs4,t),i&&(yield)),this.uvs5&&(e.setVerticesData(si.UV5Kind,this.uvs5,t),i&&(yield)),this.uvs6&&(e.setVerticesData(si.UV6Kind,this.uvs6,t),i&&(yield)),this.colors&&(e.setVerticesData(si.ColorKind,this.colors,t),this.hasVertexAlpha&&void 0!==e.hasVertexAlpha&&(e.hasVertexAlpha=!0),i&&(yield)),this.matricesIndices&&(e.setVerticesData(si.MatricesIndicesKind,this.matricesIndices,t),i&&(yield)),this.matricesWeights&&(e.setVerticesData(si.MatricesWeightsKind,this.matricesWeights,t),i&&(yield)),this.matricesIndicesExtra&&(e.setVerticesData(si.MatricesIndicesExtraKind,this.matricesIndicesExtra,t),i&&(yield)),this.matricesWeightsExtra&&(e.setVerticesData(si.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 gi(e.materialIndex,e.verticesStart,e.verticesCount,e.indexStart,e.indexCount,t)}return this}_update(e,t,i){return this.positions&&e.updateVerticesData(si.PositionKind,this.positions,t,i),this.normals&&e.updateVerticesData(si.NormalKind,this.normals,t,i),this.tangents&&e.updateVerticesData(si.TangentKind,this.tangents,t,i),this.uvs&&e.updateVerticesData(si.UVKind,this.uvs,t,i),this.uvs2&&e.updateVerticesData(si.UV2Kind,this.uvs2,t,i),this.uvs3&&e.updateVerticesData(si.UV3Kind,this.uvs3,t,i),this.uvs4&&e.updateVerticesData(si.UV4Kind,this.uvs4,t,i),this.uvs5&&e.updateVerticesData(si.UV5Kind,this.uvs5,t,i),this.uvs6&&e.updateVerticesData(si.UV6Kind,this.uvs6,t,i),this.colors&&e.updateVerticesData(si.ColorKind,this.colors,t,i),this.matricesIndices&&e.updateVerticesData(si.MatricesIndicesKind,this.matricesIndices,t,i),this.matricesWeights&&e.updateVerticesData(si.MatricesWeightsKind,this.matricesWeights,t,i),this.matricesIndicesExtra&&e.updateVerticesData(si.MatricesIndicesExtraKind,this.matricesIndicesExtra,t,i),this.matricesWeightsExtra&&e.updateVerticesData(si.MatricesWeightsExtraKind,this.matricesWeightsExtra,t,i),this.indices&&e.setIndices(this.indices,null),this}static _TransformVector3Coordinates(e,t,i=0,n=e.length){const r=H.Vector3[0],s=H.Vector3[1];for(let a=i;a<i+n;a+=3)B.FromArrayToRef(e,a,r),B.TransformCoordinatesToRef(r,t,s),e[a]=s.x,e[a+1]=s.y,e[a+2]=s.z}static _TransformVector3Normals(e,t,i=0,n=e.length){const r=H.Vector3[0],s=H.Vector3[1];for(let a=i;a<i+n;a+=3)B.FromArrayToRef(e,a,r),B.TransformNormalToRef(r,t,s),e[a]=s.x,e[a+1]=s.y,e[a+2]=s.z}static _TransformVector4Normals(e,t,i=0,n=e.length){const r=H.Vector4[0],s=H.Vector4[1];for(let a=i;a<i+n;a+=4)G.FromArrayToRef(e,a,r),G.TransformNormalToRef(r,t,s),e[a]=s.x,e[a+1]=s.y,e[a+2]=s.z,e[a+3]=s.w}static _FlipFaces(e,t=0,i=e.length){for(let n=t;n<t+i;n+=3){const t=e[n+1];e[n+1]=e[n+2],e[n+2]=t}}transform(e){const t=e.determinant()<0;return this.positions&&Ti._TransformVector3Coordinates(this.positions,e),this.normals&&Ti._TransformVector3Normals(this.normals,e),this.tangents&&Ti._TransformVector4Normals(this.tangents,e),t&&this.indices&&Ti._FlipFaces(this.indices),this}splitBasedOnMaterialID(){if(!this.materialInfos||this.materialInfos.length<2)return[this];const e=[];for(const t of this.materialInfos){const i=new Ti;if(this.positions&&(i.positions=this.positions.slice(3*t.verticesStart,3*(t.verticesCount+t.verticesStart))),this.normals&&(i.normals=this.normals.slice(3*t.verticesStart,3*(t.verticesCount+t.verticesStart))),this.tangents&&(i.tangents=this.tangents.slice(4*t.verticesStart,4*(t.verticesCount+t.verticesStart))),this.colors&&(i.colors=this.colors.slice(4*t.verticesStart,4*(t.verticesCount+t.verticesStart))),this.uvs&&(i.uvs=this.uvs.slice(2*t.verticesStart,2*(t.verticesCount+t.verticesStart))),this.uvs2&&(i.uvs2=this.uvs2.slice(2*t.verticesStart,2*(t.verticesCount+t.verticesStart))),this.uvs3&&(i.uvs3=this.uvs3.slice(2*t.verticesStart,2*(t.verticesCount+t.verticesStart))),this.uvs4&&(i.uvs4=this.uvs4.slice(2*t.verticesStart,2*(t.verticesCount+t.verticesStart))),this.uvs5&&(i.uvs5=this.uvs5.slice(2*t.verticesStart,2*(t.verticesCount+t.verticesStart))),this.uvs6&&(i.uvs6=this.uvs6.slice(2*t.verticesStart,2*(t.verticesCount+t.verticesStart))),this.matricesIndices&&(i.matricesIndices=this.matricesIndices.slice(4*t.verticesStart,4*(t.verticesCount+t.verticesStart))),this.matricesIndicesExtra&&(i.matricesIndicesExtra=this.matricesIndicesExtra.slice(4*t.verticesStart,4*(t.verticesCount+t.verticesStart))),this.matricesWeights&&(i.matricesWeights=this.matricesWeights.slice(4*t.verticesStart,4*(t.verticesCount+t.verticesStart))),this.matricesWeightsExtra&&(i.matricesWeightsExtra=this.matricesWeightsExtra.slice(4*t.verticesStart,4*(t.verticesCount+t.verticesStart))),this.indices){i.indices=[];for(let e=t.indexStart;e<t.indexStart+t.indexCount;e++)i.indices.push(this.indices[e]-t.verticesStart)}const n=new Ei;n.indexStart=0,n.indexCount=i.indices?i.indices.length:0,n.materialIndex=t.materialIndex,n.verticesStart=0,n.verticesCount=(i.positions?i.positions.length:0)/3,i.materialInfos=[n],e.push(i)}return e}merge(e,t=!1,i=!1,n=!1,r=!1){const s=Array.isArray(e)?e.map((e=>({vertexData:e}))):[{vertexData:e}];return Qt(this._mergeCoroutine(void 0,s,t,!1,i,n,r))}*_mergeCoroutine(e,t,i=!1,n,r,s=!1,a=!1){this._validate();let o=t.map((e=>e.vertexData)),l=this;if(a)for(const e of o)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 o)if(e)if(a)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(s){let i=0,n=0,r=0;const s=[];let a=null;const c=[];for(const t of this.splitBasedOnMaterialID())c.push({vertexData:t,transform:e});for(const e of t)if(e.vertexData)for(const t of e.vertexData.splitBasedOnMaterialID())c.push({vertexData:t,transform:e.transform});c.sort(((e,t)=>{const i=e.vertexData.materialInfos?e.vertexData.materialInfos[0].materialIndex:0,n=t.vertexData.materialInfos?t.vertexData.materialInfos[0].materialIndex:0;return i>n?1:i===n?0:-1}));for(const e of c){const t=e.vertexData;if(i=t.materialInfos?t.materialInfos[0].materialIndex:0,a&&a.materialIndex===i)a.indexCount+=t.indices.length,a.verticesCount+=t.positions.length/3;else{const e=new Ei;e.materialIndex=i,e.indexStart=n,e.indexCount=t.indices.length,e.verticesStart=r,e.verticesCount=t.positions.length/3,s.push(e),a=e}n+=t.indices.length,r+=t.positions.length/3}const h=c.splice(0,1)[0];l=h.vertexData,e=h.transform,o=c.map((e=>e.vertexData)),t=c,this.materialInfos=s}const c=o.reduce(((e,t)=>e+(t.indices?.length??0)),l.indices?.length??0);let h=r||o.some((e=>e.indices===l.indices))?l.indices?.slice():l.indices;if(c>0){let r=h?.length??0;if(h||(h=new Array(c)),h.length!==c){if(Array.isArray(h))h.length=c;else{const e=i||h instanceof Uint32Array?new Uint32Array(c):new Uint16Array(c);e.set(h),h=e}e&&e.determinant()<0&&Ti._FlipFaces(h,0,r)}let s=l.positions?l.positions.length/3:0;for(const{vertexData:e,transform:i}of t)if(e.indices){for(let t=0;t<e.indices.length;t++)h[r+t]=e.indices[t]+s;i&&i.determinant()<0&&Ti._FlipFaces(h,r,e.indices.length),s+=e.positions.length/3,r+=e.indices.length,n&&(yield)}}return this.indices=h,this.positions=Ti._MergeElement(si.PositionKind,l.positions,e,t.map((e=>[e.vertexData.positions,e.transform]))),n&&(yield),l.normals&&(this.normals=Ti._MergeElement(si.NormalKind,l.normals,e,t.map((e=>[e.vertexData.normals,e.transform]))),n&&(yield)),l.tangents&&(this.tangents=Ti._MergeElement(si.TangentKind,l.tangents,e,t.map((e=>[e.vertexData.tangents,e.transform]))),n&&(yield)),l.uvs&&(this.uvs=Ti._MergeElement(si.UVKind,l.uvs,e,t.map((e=>[e.vertexData.uvs,e.transform]))),n&&(yield)),l.uvs2&&(this.uvs2=Ti._MergeElement(si.UV2Kind,l.uvs2,e,t.map((e=>[e.vertexData.uvs2,e.transform]))),n&&(yield)),l.uvs3&&(this.uvs3=Ti._MergeElement(si.UV3Kind,l.uvs3,e,t.map((e=>[e.vertexData.uvs3,e.transform]))),n&&(yield)),l.uvs4&&(this.uvs4=Ti._MergeElement(si.UV4Kind,l.uvs4,e,t.map((e=>[e.vertexData.uvs4,e.transform]))),n&&(yield)),l.uvs5&&(this.uvs5=Ti._MergeElement(si.UV5Kind,l.uvs5,e,t.map((e=>[e.vertexData.uvs5,e.transform]))),n&&(yield)),l.uvs6&&(this.uvs6=Ti._MergeElement(si.UV6Kind,l.uvs6,e,t.map((e=>[e.vertexData.uvs6,e.transform]))),n&&(yield)),l.colors&&(this.colors=Ti._MergeElement(si.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))),n&&(yield)),l.matricesIndices&&(this.matricesIndices=Ti._MergeElement(si.MatricesIndicesKind,l.matricesIndices,e,t.map((e=>[e.vertexData.matricesIndices,e.transform]))),n&&(yield)),l.matricesWeights&&(this.matricesWeights=Ti._MergeElement(si.MatricesWeightsKind,l.matricesWeights,e,t.map((e=>[e.vertexData.matricesWeights,e.transform]))),n&&(yield)),l.matricesIndicesExtra&&(this.matricesIndicesExtra=Ti._MergeElement(si.MatricesIndicesExtraKind,l.matricesIndicesExtra,e,t.map((e=>[e.vertexData.matricesIndicesExtra,e.transform]))),n&&(yield)),l.matricesWeightsExtra&&(this.matricesWeightsExtra=Ti._MergeElement(si.MatricesWeightsExtraKind,l.matricesWeightsExtra,e,t.map((e=>[e.vertexData.matricesWeightsExtra,e.transform])))),this}static _MergeElement(e,t,i,n){const r=n.filter((e=>null!==e[0]&&void 0!==e[0]));if(!t&&0==r.length)return t;if(!t)return this._MergeElement(e,r[0][0],r[0][1],r.slice(1));const s=r.reduce(((e,t)=>e+t[0].length),t.length),a=e===si.PositionKind?Ti._TransformVector3Coordinates:e===si.NormalKind?Ti._TransformVector3Normals:e===si.TangentKind?Ti._TransformVector4Normals:()=>{};if(t instanceof Float32Array){const e=new Float32Array(s);e.set(t),i&&a(e,i,0,t.length);let n=t.length;for(const[t,i]of r)e.set(t,n),i&&a(e,i,n,t.length),n+=t.length;return e}{const e=new Array(s);for(let i=0;i<t.length;i++)e[i]=t[i];i&&a(e,i,0,t.length);let n=t.length;for(const[t,i]of r){for(let i=0;i<t.length;i++)e[n+i]=t[i];i&&a(e,i,n,t.length),n+=t.length}return e}}_validate(){if(!this.positions)throw new Te("Positions are required",Ee.MeshInvalidPositionsError);const e=(e,t)=>{const i=si.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(si.PositionKind,this.positions),i=(i,n)=>{const r=e(i,n);if(r!==t)throw new Error("The "+i+"s element count ("+r+") does not match the positions count ("+t+")")};this.normals&&i(si.NormalKind,this.normals),this.tangents&&i(si.TangentKind,this.tangents),this.uvs&&i(si.UVKind,this.uvs),this.uvs2&&i(si.UV2Kind,this.uvs2),this.uvs3&&i(si.UV3Kind,this.uvs3),this.uvs4&&i(si.UV4Kind,this.uvs4),this.uvs5&&i(si.UV5Kind,this.uvs5),this.uvs6&&i(si.UV6Kind,this.uvs6),this.colors&&i(si.ColorKind,this.colors),this.matricesIndices&&i(si.MatricesIndicesKind,this.matricesIndices),this.matricesWeights&&i(si.MatricesWeightsKind,this.matricesWeights),this.matricesIndicesExtra&&i(si.MatricesIndicesExtraKind,this.matricesIndicesExtra),this.matricesWeightsExtra&&i(si.MatricesWeightsExtraKind,this.matricesWeightsExtra)}clone(){const e=this.serialize();return Ti.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 Ti._ExtractFrom(e,t,i)}static ExtractFromGeometry(e,t,i){return Ti._ExtractFrom(e,t,i)}static _ExtractFrom(e,t,i){const n=new Ti;if(e.isVerticesDataPresent(si.PositionKind)&&(n.positions=e.getVerticesData(si.PositionKind,t,i)),e.isVerticesDataPresent(si.NormalKind)&&(n.normals=e.getVerticesData(si.NormalKind,t,i)),e.isVerticesDataPresent(si.TangentKind)&&(n.tangents=e.getVerticesData(si.TangentKind,t,i)),e.isVerticesDataPresent(si.UVKind)&&(n.uvs=e.getVerticesData(si.UVKind,t,i)),e.isVerticesDataPresent(si.UV2Kind)&&(n.uvs2=e.getVerticesData(si.UV2Kind,t,i)),e.isVerticesDataPresent(si.UV3Kind)&&(n.uvs3=e.getVerticesData(si.UV3Kind,t,i)),e.isVerticesDataPresent(si.UV4Kind)&&(n.uvs4=e.getVerticesData(si.UV4Kind,t,i)),e.isVerticesDataPresent(si.UV5Kind)&&(n.uvs5=e.getVerticesData(si.UV5Kind,t,i)),e.isVerticesDataPresent(si.UV6Kind)&&(n.uvs6=e.getVerticesData(si.UV6Kind,t,i)),e.isVerticesDataPresent(si.ColorKind)){const r=e.geometry||e,s=r.getVertexBuffer(si.ColorKind),a=r.getVerticesData(si.ColorKind,t,i);if(3===s.getSize()){const e=new Float32Array(4*a.length/3);for(let t=0,i=0;t<a.length;t+=3,i+=4)e[i]=a[t],e[i+1]=a[t+1],e[i+2]=a[t+2],e[i+3]=1;n.colors=e}else{if(4!==s.getSize())throw new Error(`Unexpected number of color components: ${s.getSize()}`);n.colors=a}}return e.isVerticesDataPresent(si.MatricesIndicesKind)&&(n.matricesIndices=e.getVerticesData(si.MatricesIndicesKind,t,i)),e.isVerticesDataPresent(si.MatricesWeightsKind)&&(n.matricesWeights=e.getVerticesData(si.MatricesWeightsKind,t,i)),e.isVerticesDataPresent(si.MatricesIndicesExtraKind)&&(n.matricesIndicesExtra=e.getVerticesData(si.MatricesIndicesExtraKind,t,i)),e.isVerticesDataPresent(si.MatricesWeightsExtraKind)&&(n.matricesWeightsExtra=e.getVerticesData(si.MatricesWeightsExtraKind,t,i)),n.indices=e.getIndices(t,i),n}static CreateRibbon(e){throw Y("ribbonBuilder")}static CreateBox(e){throw Y("boxBuilder")}static CreateTiledBox(e){throw Y("tiledBoxBuilder")}static CreateTiledPlane(e){throw Y("tiledPlaneBuilder")}static CreateSphere(e){throw Y("sphereBuilder")}static CreateCylinder(e){throw Y("cylinderBuilder")}static CreateTorus(e){throw Y("torusBuilder")}static CreateLineSystem(e){throw Y("linesBuilder")}static CreateDashedLines(e){throw Y("linesBuilder")}static CreateGround(e){throw Y("groundBuilder")}static CreateTiledGround(e){throw Y("groundBuilder")}static CreateGroundFromHeightMap(e){throw Y("groundBuilder")}static CreatePlane(e){throw Y("planeBuilder")}static CreateDisc(e){throw Y("discBuilder")}static CreatePolygon(e,t,i,n,r,s,a){throw Y("polygonBuilder")}static CreateIcoSphere(e){throw Y("icoSphereBuilder")}static CreatePolyhedron(e){throw Y("polyhedronBuilder")}static CreateCapsule(e={orientation:B.Up(),subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6}){throw Y("capsuleBuilder")}static CreateTorusKnot(e){throw Y("torusKnotBuilder")}static ComputeNormals(e,t,i,n){let r=0,s=0,a=0,o=0,l=0,c=0,h=0,d=0,u=0,f=0,_=0,m=0,p=0,g=0,E=0,T=0,A=0,v=0,R=0,S=0,I=!1,C=!1,M=!1,x=!1,b=1,y=0,O=null;n&&(I=!!n.facetNormals,C=!!n.facetPositions,M=!!n.facetPartitioning,b=!0===n.useRightHandedSystem?-1:1,y=n.ratio||0,x=!!n.depthSort,O=n.distanceTo,x&&void 0===O&&(O=B.Zero()));let D=0,N=0,P=0,L=0;for(M&&n&&n.bbSize&&(D=n.subDiv.X*y/n.bbSize.x,N=n.subDiv.Y*y/n.bbSize.y,P=n.subDiv.Z*y/n.bbSize.z,L=n.subDiv.max*n.subDiv.max,n.facetPartitioning.length=0),r=0;r<e.length;r++)i[r]=0;const F=t.length/3|0;for(r=0;r<F;r++){if(m=3*t[3*r],p=m+1,g=m+2,E=3*t[3*r+1],T=E+1,A=E+2,v=3*t[3*r+2],R=v+1,S=v+2,s=e[m]-e[E],a=e[p]-e[T],o=e[g]-e[A],l=e[v]-e[E],c=e[R]-e[T],h=e[S]-e[A],d=b*(a*h-o*c),u=b*(o*l-s*h),f=b*(s*c-a*l),_=Math.sqrt(d*d+u*u+f*f),_=0===_?1:_,d/=_,u/=_,f/=_,I&&n&&(n.facetNormals[r].x=d,n.facetNormals[r].y=u,n.facetNormals[r].z=f),C&&n&&(n.facetPositions[r].x=(e[m]+e[E]+e[v])/3,n.facetPositions[r].y=(e[p]+e[T]+e[R])/3,n.facetPositions[r].z=(e[g]+e[A]+e[S])/3),M&&n){const t=Math.floor((n.facetPositions[r].x-n.bInfo.minimum.x*y)*D),i=Math.floor((n.facetPositions[r].y-n.bInfo.minimum.y*y)*N),s=Math.floor((n.facetPositions[r].z-n.bInfo.minimum.z*y)*P),a=Math.floor((e[m]-n.bInfo.minimum.x*y)*D),o=Math.floor((e[p]-n.bInfo.minimum.y*y)*N),l=Math.floor((e[g]-n.bInfo.minimum.z*y)*P),c=Math.floor((e[E]-n.bInfo.minimum.x*y)*D),h=Math.floor((e[T]-n.bInfo.minimum.y*y)*N),d=Math.floor((e[A]-n.bInfo.minimum.z*y)*P),u=Math.floor((e[v]-n.bInfo.minimum.x*y)*D),f=Math.floor((e[R]-n.bInfo.minimum.y*y)*N),_=Math.floor((e[S]-n.bInfo.minimum.z*y)*P),I=a+n.subDiv.max*o+L*l,C=c+n.subDiv.max*h+L*d,M=u+n.subDiv.max*f+L*_,x=t+n.subDiv.max*i+L*s;n.facetPartitioning[x]=n.facetPartitioning[x]?n.facetPartitioning[x]:new Array,n.facetPartitioning[I]=n.facetPartitioning[I]?n.facetPartitioning[I]:new Array,n.facetPartitioning[C]=n.facetPartitioning[C]?n.facetPartitioning[C]:new Array,n.facetPartitioning[M]=n.facetPartitioning[M]?n.facetPartitioning[M]:new Array,n.facetPartitioning[I].push(r),C!=I&&n.facetPartitioning[C].push(r),M!=C&&M!=I&&n.facetPartitioning[M].push(r),x!=I&&x!=C&&x!=M&&n.facetPartitioning[x].push(r)}if(x&&n&&n.facetPositions){const e=n.depthSortedFacets[r];e.ind=3*r,e.sqDistance=B.DistanceSquared(n.facetPositions[r],O)}i[m]+=d,i[p]+=u,i[g]+=f,i[E]+=d,i[T]+=u,i[A]+=f,i[v]+=d,i[R]+=u,i[S]+=f}for(r=0;r<i.length/3;r++)d=i[3*r],u=i[3*r+1],f=i[3*r+2],_=Math.sqrt(d*d+u*u+f*f),_=0===_?1:_,d/=_,u/=_,f/=_,i[3*r]=d,i[3*r+1]=u,i[3*r+2]=f}static _ComputeSides(e,t,i,n,r,s,a){const o=i.length,l=n.length;let c,h;switch(e=e||Ti.DEFAULTSIDE){case Ti.FRONTSIDE:break;case Ti.BACKSIDE:for(c=0;c<o;c+=3){const e=i[c];i[c]=i[c+2],i[c+2]=e}for(h=0;h<l;h++)n[h]=-n[h];break;case Ti.DOUBLESIDE:{const e=t.length,d=e/3;for(let i=0;i<e;i++)t[e+i]=t[i];for(c=0;c<o;c+=3)i[c+o]=i[c+2]+d,i[c+1+o]=i[c+1]+d,i[c+2+o]=i[c]+d;for(h=0;h<l;h++)n[l+h]=-n[h];const u=r.length;let f=0;for(f=0;f<u;f++)r[f+u]=r[f];for(s=s||new G(0,0,1,1),a=a||new G(0,0,1,1),f=0,c=0;c<u/2;c++)r[f]=s.x+(s.z-s.x)*r[f],r[f+1]=s.y+(s.w-s.y)*r[f+1],r[f+u]=a.x+(a.z-a.x)*r[f+u],r[f+u+1]=a.y+(a.w-a.y)*r[f+u+1],f+=2;break}}}static Parse(e){const t=new Ti,i=e.positions;i&&t.set(i,si.PositionKind);const n=e.normals;n&&t.set(n,si.NormalKind);const r=e.tangents;r&&t.set(r,si.TangentKind);const s=e.uvs;s&&t.set(s,si.UVKind);const a=e.uvs2;a&&t.set(a,si.UV2Kind);const o=e.uvs3;o&&t.set(o,si.UV3Kind);const l=e.uvs4;l&&t.set(l,si.UV4Kind);const c=e.uvs5;c&&t.set(c,si.UV5Kind);const h=e.uvs6;h&&t.set(h,si.UV6Kind);const d=e.colors;d&&(t.set(te.CheckColors4(d,i.length/3),si.ColorKind),void 0!==e.hasVertexAlpha&&(t.hasVertexAlpha=e.hasVertexAlpha));const u=e.matricesIndices;u&&t.set(u,si.MatricesIndicesKind);const f=e.matricesWeights;f&&t.set(f,si.MatricesWeightsKind);const _=e.indices;_&&(t.indices=_);const m=e.materialInfos;if(m){t.materialInfos=[];for(const e of m){const i=new Ei;i.indexCount=e.indexCount,i.indexStart=e.indexStart,i.verticesCount=e.verticesCount,i.verticesStart=e.verticesStart,i.materialIndex=e.materialIndex,t.materialInfos.push(i)}}return t}static ImportVertexData(e,t){const i=Ti.Parse(e);t.setAllVerticesData(i,e.updatable)}}Ti.FRONTSIDE=0,Ti.BACKSIDE=1,Ti.DOUBLESIDE=2,Ti.DEFAULTSIDE=0,Ti._UniqueIDGenerator=0,e([_.filter(((...[e])=>!Array.isArray(e)))],Ti,"_TransformVector3Coordinates",null),e([_.filter(((...[e])=>!Array.isArray(e)))],Ti,"_TransformVector3Normals",null),e([_.filter(((...[e])=>!Array.isArray(e)))],Ti,"_TransformVector4Normals",null),e([_.filter(((...[e])=>!Array.isArray(e)))],Ti,"_FlipFaces",null);class Ai{static get ForceFullSceneLoadingForIncremental(){return Ai._ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){Ai._ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return Ai._ShowLoadingScreen}static set ShowLoadingScreen(e){Ai._ShowLoadingScreen=e}static get loggingLevel(){return Ai._LoggingLevel}static set loggingLevel(e){Ai._LoggingLevel=e}static get CleanBoneMatrixWeights(){return Ai._CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){Ai._CleanBoneMatrixWeights=e}}Ai._ForceFullSceneLoadingForIncremental=!1,Ai._ShowLoadingScreen=!0,Ai._CleanBoneMatrixWeights=!1,Ai._LoggingLevel=Ze.SCENELOADER_NO_LOGGING;class vi{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 vi(vi.RandomId(),e.getScene());return t.applyToMesh(e),t}get meshes(){return this._meshes}constructor(e,t,i,n=!1,r=null){this.delayLoadState=Ze.DELAYLOADSTATE_NONE,this._totalVertices=0,this._isDisposed=!1,this._indexBufferIsUpdatable=!1,this._positionsCache=[],this._parentContainer=null,this.useBoundingInfoFromGeometry=!1,this._scene=t||y.LastCreatedScene,this._scene&&(this.id=e,this.uniqueId=this._scene.getUniqueId(),this._engine=this._scene.getEngine(),this._meshes=[],this._vertexBuffers={},this._indices=[],this._updatable=n,i?this.setAllVerticesData(i,n):this._totalVertices=0,this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObjects={}),r&&(this.applyToMesh(r),r.computeWorldMatrix(!0)))}get extend(){return this._extend}getScene(){return this._scene}getEngine(){return this._engine}isReady(){return this.delayLoadState===Ze.DELAYLOADSTATE_LOADED||this.delayLoadState===Ze.DELAYLOADSTATE_NONE}get doNotSerialize(){for(let e=0;e<this._meshes.length;e++)if(!this._meshes[e].doNotSerialize)return!1;return!0}_rebuild(){this._vertexArrayObjects&&(this._vertexArrayObjects={}),0!==this._meshes.length&&this._indices&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,this._updatable,"Geometry_"+this.id+"_IndexBuffer"));const e=new Set;for(const t in this._vertexBuffers)e.add(this._vertexBuffers[t].getWrapperBuffer());e.forEach((e=>{e._rebuild()}))}setAllVerticesData(e,t){e.applyToGeometry(this,t),this._notifyUpdate()}setVerticesData(e,t,i=!1,n){i&&Array.isArray(t)&&(t=new Float32Array(t));const r=new si(this._engine,t,e,{updatable:i,postponeInternalCreation:0===this._meshes.length,stride:n,label:"Geometry_"+this.id+"_"+e});this.setVerticesBuffer(r)}removeVerticesData(e){this._vertexBuffers[e]&&(this._vertexBuffers[e].dispose(),delete this._vertexBuffers[e]),this._vertexArrayObjects&&this._disposeVertexArrayObjects()}setVerticesBuffer(e,t=null,i=!0){const n=e.getKind();this._vertexBuffers[n]&&i&&this._vertexBuffers[n].dispose(),e._buffer&&e._buffer._increaseReferences(),this._vertexBuffers[n]=e;const r=this._meshes,s=r.length;if(n===si.PositionKind){this._totalVertices=t??e._maxVerticesCount,this._updateExtend(e.getFloatData(this._totalVertices)),this._resetPointsArrayCache();const i=this._extend&&this._extend.minimum||new B(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),n=this._extend&&this._extend.maximum||new B(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE);for(let e=0;e<s;e++){const t=r[e];t.buildBoundingInfo(i,n),t._createGlobalSubMesh(t.isUnIndexed),t.computeWorldMatrix(!0),t.synchronizeInstances()}}this._notifyUpdate(n)}updateVerticesDataDirectly(e,t,i,n=!1){const r=this.getVertexBuffer(e);r&&(r.updateDirectly(t,i,n),this._notifyUpdate(e))}updateVerticesData(e,t,i=!1){const n=this.getVertexBuffer(e);n&&(n.update(t),e===si.PositionKind&&this._updateBoundingInfo(i,t),this._notifyUpdate(e))}_updateBoundingInfo(e,t){if(e&&this._updateExtend(t),this._resetPointsArrayCache(),e){const e=this._meshes;for(const t of e){t.hasBoundingInfo?t.getBoundingInfo().reConstruct(this._extend.minimum,this._extend.maximum):t.buildBoundingInfo(this._extend.minimum,this._extend.maximum);const e=t.subMeshes;for(const t of e)t.refreshBoundingInfo()}}}_bind(e,t,i,n){if(!e)return;void 0===t&&(t=this._indexBuffer);const r=this.getVertexBuffers();if(!r)return;if(t!=this._indexBuffer||!this._vertexArrayObjects&&!n)return void this._engine.bindBuffers(r,t,e,i);const s=n||this._vertexArrayObjects,a=this._engine;s[e.key]||(s[e.key]=a.recordVertexArrayObject(r,t,e,i)),a.bindVertexArrayObject(s[e.key],t)}getTotalVertices(){return this.isReady()?this._totalVertices:0}getVerticesData(e,t,i){const n=this.getVertexBuffer(e);return n?n.getFloatData(this._totalVertices,i||t&&1!==this._meshes.length):null}copyVerticesData(e,t){const i=this.getVertexBuffer(e);if(!i)return;t[e]||=new Float32Array(this._totalVertices*i.getSize());const n=i.getData();n&&function(e,t,i,n,r,s,a,o){const l=t*si.GetTypeByteLength(i),c=a*t;if(o.length!==c)throw new Error("Output length is not valid");if(i===si.FLOAT&&r===l)if(e instanceof Array){const t=n/4;o.set(e,t)}else if(e instanceof ArrayBuffer){const t=new Float32Array(e,n,c);o.set(t)}else{const t=e.byteOffset+n;if(t%4)return de.Warn("CopyFloatData: copied misaligned data."),void o.set(new Float32Array(e.buffer.slice(t,t+4*c)));const i=new Float32Array(e.buffer,t,c);o.set(i)}else si.ForEach(e,n,r,t,i,c,s,((e,t)=>o[t]=e))}(n,i.getSize(),i.type,i.byteOffset,i.byteStride,i.normalized,this._totalVertices,t[e])}isVertexBufferUpdatable(e){const t=this._vertexBuffers[e];return!!t&&t.isUpdatable()}getVertexBuffer(e){return this.isReady()?this._vertexBuffers[e]:null}getVertexBuffers(){return this.isReady()?this._vertexBuffers:null}isVerticesDataPresent(e){return this._vertexBuffers?void 0!==this._vertexBuffers[e]:!!this._delayInfo&&-1!==this._delayInfo.indexOf(e)}getVerticesDataKinds(){const e=[];let t;if(!this._vertexBuffers&&this._delayInfo)for(t in this._delayInfo)e.push(t);else for(t in this._vertexBuffers)e.push(t);return e}updateIndices(e,t,i=!1){if(this._indexBuffer)if(this._indexBufferIsUpdatable){const n=e.length!==this._indices.length;if(i||(this._indices=e.slice()),this._engine.updateDynamicIndexBuffer(this._indexBuffer,e,t),n)for(const e of this._meshes)e._createGlobalSubMesh(!0)}else this.setIndices(e,null,!0)}setIndexBuffer(e,t,i){this._indices=[],this._indexBufferIsUpdatable=!1,this._indexBuffer=e,this._totalVertices=t,this._totalIndices=i,e.is32Bits||=this._totalIndices>65535;for(const e of this._meshes)e._createGlobalSubMesh(!0),e.synchronizeInstances();this._notifyUpdate()}setIndices(e,t=null,i=!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(!0),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,n=i.indexOf(e);-1!==n&&(i.splice(n,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(si.PositionKind)))return;this._extend=mi(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===si.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){this.delayLoadState!==Ze.DELAYLOADSTATE_LOADING&&(this.isReady()?t&&t():(this.delayLoadState=Ze.DELAYLOADSTATE_LOADING,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=Ze.DELAYLOADSTATE_LOADED,this._delayInfo=[],e.removePendingData(this);const n=this._meshes,r=n.length;for(let e=0;e<r;e++)this._applyToMesh(n[e]);t&&t()}),void 0,!0))}toLeftHanded(){const e=this.getIndices(!1);if(null!=e&&e.length>0){for(let t=0;t<e.length;t+=3){const i=e[t+0];e[t+0]=e[t+2],e[t+2]=i}this.setIndices(e)}const t=this.getVerticesData(si.PositionKind,!1);if(null!=t&&t.length>0){for(let e=0;e<t.length;e+=3)t[e+2]=-t[e+2];this.setVerticesData(si.PositionKind,t,!1)}const i=this.getVerticesData(si.NormalKind,!1);if(null!=i&&i.length>0){for(let e=0;e<i.length;e+=3)i[e+2]=-i[e+2];this.setVerticesData(si.NormalKind,i,!1)}}_resetPointsArrayCache(){this._positions=null}_generatePointsArray(){if(this._positions)return!0;const e=this.getVerticesData(si.PositionKind);if(!e||0===e.length)return!1;for(let t=3*this._positionsCache.length,i=this._positionsCache.length;t<e.length;t+=3,++i)this._positionsCache[i]=B.FromArray(e,t);for(let t=0,i=0;t<e.length;t+=3,++i)this._positionsCache[i].set(e[0+t],e[1+t],e[2+t]);return this._positionsCache.length=e.length/3,this._positions=this._positionsCache,!0}isDisposed(){return this._isDisposed}_disposeVertexArrayObjects(){if(this._vertexArrayObjects){for(const e in this._vertexArrayObjects)this._engine.releaseVertexArrayObject(this._vertexArrayObjects[e]);this._vertexArrayObjects={};const e=this._meshes,t=e.length;for(let i=0;i<t;i++)e[i]._invalidateInstanceVertexArrayObject()}}dispose(){const e=this._meshes,t=e.length;let i;for(i=0;i<t;i++)this.releaseForMesh(e[i]);this._meshes.length=0,this._disposeVertexArrayObjects();for(const e in this._vertexBuffers)this._vertexBuffers[e].dispose();if(this._vertexBuffers={},this._totalVertices=0,this._indexBuffer&&this._engine._releaseBuffer(this._indexBuffer),this._indexBuffer=null,this._indices=[],this.delayLoadState=Ze.DELAYLOADSTATE_NONE,this.delayLoadingFile=null,this._delayLoadingFunction=null,this._delayInfo=[],this._boundingInfo=null,this._scene.removeGeometry(this),this._parentContainer){const e=this._parentContainer.geometries.indexOf(this);e>-1&&this._parentContainer.geometries.splice(e,1),this._parentContainer=null}this._isDisposed=!0}copy(e){const t=new Ti;t.indices=[];const i=this.getIndices();if(i)for(let e=0;e<i.length;e++)t.indices.push(i[e]);let n,r=!1,s=!1;for(n in this._vertexBuffers){const e=this.getVerticesData(n);if(e&&(e instanceof Float32Array?t.set(new Float32Array(e),n):t.set(e.slice(0),n),!s)){const e=this.getVertexBuffer(n);e&&(r=e.isUpdatable(),s=!r)}}const a=new vi(e,this._scene,t,r);for(n in a.delayLoadState=this.delayLoadState,a.delayLoadingFile=this.delayLoadingFile,a._delayLoadingFunction=this._delayLoadingFunction,this._delayInfo)a._delayInfo=a._delayInfo||[],a._delayInfo.push(n);return a._boundingInfo=new fi(this._extend.minimum,this._extend.maximum),a}serialize(){const e={};return e.id=this.id,e.uniqueId=this.uniqueId,e.updatable=this._updatable,q&&q.HasTags(this)&&(e.tags=q.GetTags(this)),e}_toNumberArray(e){return Array.isArray(e)?e:Array.prototype.slice.call(e)}clearCachedData(){this._indices=[],this._resetPointsArrayCache();for(const e in this._vertexBuffers)Object.prototype.hasOwnProperty.call(this._vertexBuffers,e)&&(this._vertexBuffers[e]._buffer._data=null)}serializeVerticeData(){const e=this.serialize();return this.isVerticesDataPresent(si.PositionKind)&&(e.positions=this._toNumberArray(this.getVerticesData(si.PositionKind)),this.isVertexBufferUpdatable(si.PositionKind)&&(e.positions._updatable=!0)),this.isVerticesDataPresent(si.NormalKind)&&(e.normals=this._toNumberArray(this.getVerticesData(si.NormalKind)),this.isVertexBufferUpdatable(si.NormalKind)&&(e.normals._updatable=!0)),this.isVerticesDataPresent(si.TangentKind)&&(e.tangents=this._toNumberArray(this.getVerticesData(si.TangentKind)),this.isVertexBufferUpdatable(si.TangentKind)&&(e.tangents._updatable=!0)),this.isVerticesDataPresent(si.UVKind)&&(e.uvs=this._toNumberArray(this.getVerticesData(si.UVKind)),this.isVertexBufferUpdatable(si.UVKind)&&(e.uvs._updatable=!0)),this.isVerticesDataPresent(si.UV2Kind)&&(e.uvs2=this._toNumberArray(this.getVerticesData(si.UV2Kind)),this.isVertexBufferUpdatable(si.UV2Kind)&&(e.uvs2._updatable=!0)),this.isVerticesDataPresent(si.UV3Kind)&&(e.uvs3=this._toNumberArray(this.getVerticesData(si.UV3Kind)),this.isVertexBufferUpdatable(si.UV3Kind)&&(e.uvs3._updatable=!0)),this.isVerticesDataPresent(si.UV4Kind)&&(e.uvs4=this._toNumberArray(this.getVerticesData(si.UV4Kind)),this.isVertexBufferUpdatable(si.UV4Kind)&&(e.uvs4._updatable=!0)),this.isVerticesDataPresent(si.UV5Kind)&&(e.uvs5=this._toNumberArray(this.getVerticesData(si.UV5Kind)),this.isVertexBufferUpdatable(si.UV5Kind)&&(e.uvs5._updatable=!0)),this.isVerticesDataPresent(si.UV6Kind)&&(e.uvs6=this._toNumberArray(this.getVerticesData(si.UV6Kind)),this.isVertexBufferUpdatable(si.UV6Kind)&&(e.uvs6._updatable=!0)),this.isVerticesDataPresent(si.ColorKind)&&(e.colors=this._toNumberArray(this.getVerticesData(si.ColorKind)),this.isVertexBufferUpdatable(si.ColorKind)&&(e.colors._updatable=!0)),this.isVerticesDataPresent(si.MatricesIndicesKind)&&(e.matricesIndices=this._toNumberArray(this.getVerticesData(si.MatricesIndicesKind)),e.matricesIndices._isExpanded=!0,this.isVertexBufferUpdatable(si.MatricesIndicesKind)&&(e.matricesIndices._updatable=!0)),this.isVerticesDataPresent(si.MatricesWeightsKind)&&(e.matricesWeights=this._toNumberArray(this.getVerticesData(si.MatricesWeightsKind)),this.isVertexBufferUpdatable(si.MatricesWeightsKind)&&(e.matricesWeights._updatable=!0)),e.indices=this._toNumberArray(this.getIndices()),e}static ExtractFromMesh(e,t){const i=e._geometry;return i?i.copy(t):null}static RandomId(){return Yt.RandomId()}static _GetGeometryByLoadedUniqueId(e,t){for(let i=0;i<t.geometries.length;i++)if(t.geometries[i]._loadedUniqueId===e)return t.geometries[i];return null}static _ImportGeometry(e,t){const i=t.getScene(),n=e.geometryUniqueId,r=e.geometryId;if(n||r){const e=n?this._GetGeometryByLoadedUniqueId(n,i):i.getGeometryById(r);e&&e.applyToMesh(t)}else if(e instanceof ArrayBuffer){const i=t._binaryInfo;if(i.positionsAttrDesc&&i.positionsAttrDesc.count>0){const n=new Float32Array(e,i.positionsAttrDesc.offset,i.positionsAttrDesc.count);t.setVerticesData(si.PositionKind,n,!1)}if(i.normalsAttrDesc&&i.normalsAttrDesc.count>0){const n=new Float32Array(e,i.normalsAttrDesc.offset,i.normalsAttrDesc.count);t.setVerticesData(si.NormalKind,n,!1)}if(i.tangetsAttrDesc&&i.tangetsAttrDesc.count>0){const n=new Float32Array(e,i.tangetsAttrDesc.offset,i.tangetsAttrDesc.count);t.setVerticesData(si.TangentKind,n,!1)}if(i.uvsAttrDesc&&i.uvsAttrDesc.count>0){const n=new Float32Array(e,i.uvsAttrDesc.offset,i.uvsAttrDesc.count);t.setVerticesData(si.UVKind,n,!1)}if(i.uvs2AttrDesc&&i.uvs2AttrDesc.count>0){const n=new Float32Array(e,i.uvs2AttrDesc.offset,i.uvs2AttrDesc.count);t.setVerticesData(si.UV2Kind,n,!1)}if(i.uvs3AttrDesc&&i.uvs3AttrDesc.count>0){const n=new Float32Array(e,i.uvs3AttrDesc.offset,i.uvs3AttrDesc.count);t.setVerticesData(si.UV3Kind,n,!1)}if(i.uvs4AttrDesc&&i.uvs4AttrDesc.count>0){const n=new Float32Array(e,i.uvs4AttrDesc.offset,i.uvs4AttrDesc.count);t.setVerticesData(si.UV4Kind,n,!1)}if(i.uvs5AttrDesc&&i.uvs5AttrDesc.count>0){const n=new Float32Array(e,i.uvs5AttrDesc.offset,i.uvs5AttrDesc.count);t.setVerticesData(si.UV5Kind,n,!1)}if(i.uvs6AttrDesc&&i.uvs6AttrDesc.count>0){const n=new Float32Array(e,i.uvs6AttrDesc.offset,i.uvs6AttrDesc.count);t.setVerticesData(si.UV6Kind,n,!1)}if(i.colorsAttrDesc&&i.colorsAttrDesc.count>0){const n=new Float32Array(e,i.colorsAttrDesc.offset,i.colorsAttrDesc.count);t.setVerticesData(si.ColorKind,n,!1,i.colorsAttrDesc.stride)}if(i.matricesIndicesAttrDesc&&i.matricesIndicesAttrDesc.count>0){const n=new Int32Array(e,i.matricesIndicesAttrDesc.offset,i.matricesIndicesAttrDesc.count),r=[];for(let e=0;e<n.length;e++){const t=n[e];r.push(255&t),r.push((65280&t)>>8),r.push((16711680&t)>>16),r.push(t>>24&255)}t.setVerticesData(si.MatricesIndicesKind,r,!1)}if(i.matricesIndicesExtraAttrDesc&&i.matricesIndicesExtraAttrDesc.count>0){const n=new Int32Array(e,i.matricesIndicesExtraAttrDesc.offset,i.matricesIndicesExtraAttrDesc.count),r=[];for(let e=0;e<n.length;e++){const t=n[e];r.push(255&t),r.push((65280&t)>>8),r.push((16711680&t)>>16),r.push(t>>24&255)}t.setVerticesData(si.MatricesIndicesExtraKind,r,!1)}if(i.matricesWeightsAttrDesc&&i.matricesWeightsAttrDesc.count>0){const n=new Float32Array(e,i.matricesWeightsAttrDesc.offset,i.matricesWeightsAttrDesc.count);t.setVerticesData(si.MatricesWeightsKind,n,!1)}if(i.indicesAttrDesc&&i.indicesAttrDesc.count>0){const n=new Int32Array(e,i.indicesAttrDesc.offset,i.indicesAttrDesc.count);t.setIndices(n,null)}if(i.subMeshesAttrDesc&&i.subMeshesAttrDesc.count>0){const n=new Int32Array(e,i.subMeshesAttrDesc.offset,5*i.subMeshesAttrDesc.count);t.subMeshes=[];for(let e=0;e<i.subMeshesAttrDesc.count;e++){const i=n[5*e+0],r=n[5*e+1],s=n[5*e+2],a=n[5*e+3],o=n[5*e+4];gi.AddToMesh(i,r,s,a,o,t)}}}else if(e.positions&&e.normals&&e.indices){if(t.setVerticesData(si.PositionKind,e.positions,e.positions._updatable),t.setVerticesData(si.NormalKind,e.normals,e.normals._updatable),e.tangents&&t.setVerticesData(si.TangentKind,e.tangents,e.tangents._updatable),e.uvs&&t.setVerticesData(si.UVKind,e.uvs,e.uvs._updatable),e.uvs2&&t.setVerticesData(si.UV2Kind,e.uvs2,e.uvs2._updatable),e.uvs3&&t.setVerticesData(si.UV3Kind,e.uvs3,e.uvs3._updatable),e.uvs4&&t.setVerticesData(si.UV4Kind,e.uvs4,e.uvs4._updatable),e.uvs5&&t.setVerticesData(si.UV5Kind,e.uvs5,e.uvs5._updatable),e.uvs6&&t.setVerticesData(si.UV6Kind,e.uvs6,e.uvs6._updatable),e.colors&&t.setVerticesData(si.ColorKind,te.CheckColors4(e.colors,e.positions.length/3),e.colors._updatable),e.matricesIndices)if(e.matricesIndices._isExpanded)delete e.matricesIndices._isExpanded,t.setVerticesData(si.MatricesIndicesKind,e.matricesIndices,e.matricesIndices._updatable);else{const i=[];for(let t=0;t<e.matricesIndices.length;t++){const n=e.matricesIndices[t];i.push(255&n),i.push((65280&n)>>8),i.push((16711680&n)>>16),i.push(n>>24&255)}t.setVerticesData(si.MatricesIndicesKind,i,e.matricesIndices._updatable)}if(e.matricesIndicesExtra)if(e.matricesIndicesExtra._isExpanded)delete e.matricesIndices._isExpanded,t.setVerticesData(si.MatricesIndicesExtraKind,e.matricesIndicesExtra,e.matricesIndicesExtra._updatable);else{const i=[];for(let t=0;t<e.matricesIndicesExtra.length;t++){const n=e.matricesIndicesExtra[t];i.push(255&n),i.push((65280&n)>>8),i.push((16711680&n)>>16),i.push(n>>24&255)}t.setVerticesData(si.MatricesIndicesExtraKind,i,e.matricesIndicesExtra._updatable)}e.matricesWeights&&(vi._CleanMatricesWeights(e,t),t.setVerticesData(si.MatricesWeightsKind,e.matricesWeights,e.matricesWeights._updatable)),e.matricesWeightsExtra&&t.setVerticesData(si.MatricesWeightsExtraKind,e.matricesWeightsExtra,e.matricesWeights._updatable),t.setIndices(e.indices,null)}if(e.subMeshes){t.subMeshes=[];for(let i=0;i<e.subMeshes.length;i++){const n=e.subMeshes[i];gi.AddToMesh(n.materialIndex,n.verticesStart,n.verticesCount,n.indexStart,n.indexCount,t)}}t._shouldGenerateFlatShading&&(t.convertToFlatShadedMesh(),t._shouldGenerateFlatShading=!1),t.computeWorldMatrix(!0),i.onMeshImportedObservable.notifyObservers(t)}static _CleanMatricesWeights(e,t){const i=.001;if(!Ai.CleanBoneMatrixWeights)return;let n=0;if(!(e.skeletonId>-1))return;{const i=t.getScene().getLastSkeletonById(e.skeletonId);if(!i)return;n=i.bones.length}const r=t.getVerticesData(si.MatricesIndicesKind),s=t.getVerticesData(si.MatricesIndicesExtraKind),a=e.matricesWeights,o=e.matricesWeightsExtra,l=e.numBoneInfluencer,c=a.length;for(let e=0;e<c;e+=4){let t=0,c=-1;for(let n=0;n<4;n++){const r=a[e+n];t+=r,r<i&&c<0&&(c=n)}if(o)for(let n=0;n<4;n++){const r=o[e+n];t+=r,r<i&&c<0&&(c=n+4)}if((c<0||c>l-1)&&(c=l-1),t>i){const i=1/t;for(let t=0;t<4;t++)a[e+t]*=i;if(o)for(let t=0;t<4;t++)o[e+t]*=i}else c>=4?(o[e+c-4]=1-t,s[e+c-4]=n):(a[e+c]=1-t,r[e+c]=n)}t.setVerticesData(si.MatricesIndicesKind,r),e.matricesWeightsExtra&&t.setVerticesData(si.MatricesIndicesExtraKind,s)}static Parse(e,t,i){const n=new vi(e.id,t,void 0,e.updatable);return n._loadedUniqueId=e.uniqueId,q&&q.AddTagsTo(n,e.tags),e.delayLoadingFile?(n.delayLoadState=Ze.DELAYLOADSTATE_NOTLOADED,n.delayLoadingFile=i+e.delayLoadingFile,n._boundingInfo=new fi(B.FromArray(e.boundingBoxMinimum),B.FromArray(e.boundingBoxMaximum)),n._delayInfo=[],e.hasUVs&&n._delayInfo.push(si.UVKind),e.hasUVs2&&n._delayInfo.push(si.UV2Kind),e.hasUVs3&&n._delayInfo.push(si.UV3Kind),e.hasUVs4&&n._delayInfo.push(si.UV4Kind),e.hasUVs5&&n._delayInfo.push(si.UV5Kind),e.hasUVs6&&n._delayInfo.push(si.UV6Kind),e.hasColors&&n._delayInfo.push(si.ColorKind),e.hasMatricesIndices&&n._delayInfo.push(si.MatricesIndicesKind),e.hasMatricesWeights&&n._delayInfo.push(si.MatricesWeightsKind),n._delayLoadingFunction=Ti.ImportVertexData):Ti.ImportVertexData(e,n),t.pushGeometry(n,!0),n}}const Ri=k.Compose(B.One(),V.FromEulerAngles(0,Math.PI,0),B.Zero());class Si extends ae{get billboardMode(){return this._billboardMode}set billboardMode(e){this._billboardMode!==e&&(this._billboardMode=e,this._cache.useBillboardPosition=!!(this._billboardMode&Si.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!==Si.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 B(0,0,1),this._up=new B(0,1,0),this._right=new B(1,0,0),this._position=B.Zero(),this._rotation=B.Zero(),this._rotationQuaternion=null,this._scaling=B.One(),this._transformToBoneReferal=null,this._isAbsoluteSynced=!1,this._billboardMode=Si.BILLBOARDMODE_NONE,this._preserveParentRotationForBillboard=!1,this.scalingDeterminant=1,this._infiniteDistance=!1,this.ignoreNonUniformScaling=!1,this.reIntegrateRotationIntoRotationQuaternion=!1,this._poseMatrix=null,this._localMatrix=k.Zero(),this._usePivotMatrix=!1,this._absolutePosition=B.Zero(),this._absoluteScaling=B.Zero(),this._absoluteRotationQuaternion=V.Identity(),this._pivotMatrix=k.Identity(),this._postMultiplyPivotMatrix=!1,this._isWorldMatrixFrozen=!1,this._indexInSceneTransformNodesArray=-1,this.onAfterWorldMatrixUpdateObservable=new g,this._nonUniformScaling=!1,i&&this.getScene().addTransformNode(this)}getClassName(){return"TransformNode"}get position(){return this._position}set position(e){this._position=e,this._isDirty=!0}isUsingPivotMatrix(){return this._usePivotMatrix}isUsingPostMultiplyPivotMatrix(){return this._postMultiplyPivotMatrix}get rotation(){return this._rotation}set rotation(e){this._rotation=e,this._rotationQuaternion=null,this._isDirty=!0}get scaling(){return this._scaling}set scaling(e){this._scaling=e,this._isDirty=!0}get rotationQuaternion(){return this._rotationQuaternion}set rotationQuaternion(e){this._rotationQuaternion=e,e&&this._rotation.setAll(0),this._isDirty=!0}get forward(){return B.TransformNormalFromFloatsToRef(0,0,this.getScene().useRightHandedSystem?-1:1,this.getWorldMatrix(),this._forward),this._forward.normalize()}get up(){return B.TransformNormalFromFloatsToRef(0,1,0,this.getWorldMatrix(),this._up),this._up.normalize()}get right(){return B.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=k.Identity()),this._poseMatrix}_isSynchronized(){const e=this._cache;return this._billboardMode===e.billboardMode&&this._billboardMode===Si.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=k.Invert(this._pivotMatrix)),this}getPivotMatrix(){return this._pivotMatrix}instantiateHierarchy(e=null,t,i){const n=this.clone("Clone of "+(this.name||this.id),e||this.parent,!0);n&&i&&i(this,n);for(const e of this.getChildTransformNodes(!0))e.instantiateHierarchy(n,t,i);return n}freezeWorldMatrix(e=null,t=!1){return e?t?(this._rotation.setAll(0),this._rotationQuaternion=this._rotationQuaternion||V.Identity(),e.decompose(this._scaling,this._rotationQuaternion,this._position),this.computeWorldMatrix(!0)):(this._worldMatrix=e,this._absolutePosition.copyFromFloats(this._worldMatrix.m[12],this._worldMatrix.m[13],this._worldMatrix.m[14]),this._afterComputeWorldMatrix()):(this._isWorldMatrixFrozen=!1,this.computeWorldMatrix(!0)),this._isDirty=!1,this._isWorldMatrixFrozen=!0,this}unfreezeWorldMatrix(){return this._isWorldMatrixFrozen=!1,this.computeWorldMatrix(!0),this}get isWorldMatrixFrozen(){return this._isWorldMatrixFrozen}getAbsolutePosition(){return this.computeWorldMatrix(),this._absolutePosition}setAbsolutePosition(e){if(!e)return this;let t,i,n;if(void 0===e.x){if(arguments.length<3)return this;t=arguments[0],i=arguments[1],n=arguments[2]}else t=e.x,i=e.y,n=e.z;if(this.parent){const e=H.Matrix[0];this.parent.getWorldMatrix().invertToRef(e),B.TransformCoordinatesFromFloatsToRef(t,i,n,e,this.position)}else this.position.x=t,this.position.y=i,this.position.z=n;return this._absolutePosition.copyFrom(e),this}setPositionWithLocalVector(e){return this.computeWorldMatrix(),this.position=B.TransformNormal(e,this._localMatrix),this}getPositionExpressedInLocalSpace(){this.computeWorldMatrix();const e=H.Matrix[0];return this._localMatrix.invertToRef(e),B.TransformNormal(this.position,e)}locallyTranslate(e){return this.computeWorldMatrix(!0),this.position=B.TransformCoordinates(e,this._localMatrix),this}lookAt(e,t=0,i=0,n=0,r=0){const s=Si._LookAtVectorCache,a=0===r?this.position:this.getAbsolutePosition();if(e.subtractToRef(a,s),this.setDirection(s,t,i,n),1===r&&this.parent)if(this.rotationQuaternion){const e=H.Matrix[0];this.rotationQuaternion.toRotationMatrix(e);const t=H.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(t),t.invert(),e.multiplyToRef(t,e),this.rotationQuaternion.fromRotationMatrix(e)}else{const e=H.Quaternion[0];V.FromEulerVectorToRef(this.rotation,e);const t=H.Matrix[0];e.toRotationMatrix(t);const i=H.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=B.Zero();return this.getDirectionToRef(e,t),t}getDirectionToRef(e,t){return B.TransformNormalToRef(e,this.getWorldMatrix(),t),this}setDirection(e,t=0,i=0,n=0){const r=-Math.atan2(e.z,e.x)+Math.PI/2,s=Math.sqrt(e.x*e.x+e.z*e.z),a=-Math.atan2(e.y,s);return this.rotationQuaternion?V.RotationYawPitchRollToRef(r+t,a+i,n,this.rotationQuaternion):(this.rotation.x=a+i,this.rotation.y=r+t,this.rotation.z=n),this}setPivotPoint(e,t=0){0==this.getScene().getRenderId()&&this.computeWorldMatrix(!0);const i=this.getWorldMatrix();if(1==t){const t=H.Matrix[0];i.invertToRef(t),e=B.TransformCoordinates(e,t)}return this.setPivotMatrix(k.Translation(-e.x,-e.y,-e.z),!0)}getPivotPoint(){const e=B.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=B.Zero();return this.getAbsolutePivotPointToRef(e),e}getAbsolutePivotPointToRef(e){return this.getPivotPointToRef(e),B.TransformCoordinatesToRef(e,this.getWorldMatrix(),e),this}markAsDirty(e){if(this._isDirty)return this;if(this._children)for(const t of this._children)t.markAsDirty(e);return super.markAsDirty(e)}setParent(e,t=!1,i=!1){if(!e&&!this.parent)return this;const n=H.Quaternion[0],r=H.Vector3[0],s=H.Vector3[1],a=H.Matrix[1];k.IdentityToRef(a);const o=H.Matrix[0];this.computeWorldMatrix(!0);let l=this.rotationQuaternion;return l||(l=Si._TmpRotation,V.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,l)),k.ComposeToRef(this.scaling,l,this.position,o),this.parent&&o.multiplyToRef(this.parent.computeWorldMatrix(!0),o),e&&(e.computeWorldMatrix(!0).invertToRef(a),o.multiplyToRef(a,o)),o.decompose(s,n,r,t?this:void 0),this.rotationQuaternion?this.rotationQuaternion.copyFrom(n):n.toEulerAnglesToRef(this.rotation),this.scaling.copyFrom(s),this.position.copyFrom(r),this.parent=e,i&&this.setPivotMatrix(k.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 n;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(),n=H.Matrix[0];i.invertToRef(n),e=B.TransformNormal(e,n),i.determinant()<0&&(t*=-1)}n=V.RotationAxisToRef(e,t,Si._RotationAxisCache),n.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}else n=V.RotationAxisToRef(e,t,Si._RotationAxisCache),this.rotationQuaternion.multiplyToRef(n,this.rotationQuaternion);return this}rotateAround(e,t,i){t.normalize(),this.rotationQuaternion||(this.rotationQuaternion=V.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z),this.rotation.setAll(0));const n=H.Vector3[0],r=H.Vector3[1],s=H.Vector3[2],a=H.Quaternion[0],o=H.Matrix[0],l=H.Matrix[1],c=H.Matrix[2],h=H.Matrix[3];return e.subtractToRef(this.position,n),k.TranslationToRef(n.x,n.y,n.z,o),k.TranslationToRef(-n.x,-n.y,-n.z,l),k.RotationAxisToRef(t,i,c),l.multiplyToRef(c,h),h.multiplyToRef(o,h),h.decompose(r,a,s),this.position.addInPlace(s),a.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion),this}translate(e,t,i){const n=e.scale(t);if(i&&0!==i)this.setAbsolutePosition(this.getAbsolutePosition().add(n));else{const e=this.getPositionExpressedInLocalSpace().add(n);this.setPositionWithLocalVector(e)}return this}addRotation(e,t,i){let n;this.rotationQuaternion?n=this.rotationQuaternion:(n=H.Quaternion[1],V.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,n));const r=H.Quaternion[0];return V.RotationYawPitchRollToRef(t,e,i,r),n.multiplyInPlace(r),this.rotationQuaternion||n.toEulerAnglesToRef(this.rotation),this}_getEffectiveParent(){return this.parent}isWorldMatrixCameraDependent(){return this._infiniteDistance&&!this.parent||this._billboardMode!==Si.BILLBOARDMODE_NONE&&!this.preserveParentRotationForBillboard}computeWorldMatrix(e=!1,t=null){if(this._isWorldMatrixFrozen&&!this._isDirty)return this._worldMatrix;const i=this.getScene().getRenderId();if(!this._isDirty&&!e&&(this._currentRenderId===i||this.isSynchronized()))return this._currentRenderId=i,this._worldMatrix;t=t||this.getScene().activeCamera,this._updateCache();const n=this._cache;n.pivotMatrixUpdated=!1,n.billboardMode=this.billboardMode,n.infiniteDistance=this.infiniteDistance,n.parent=this._parentNode,this._currentRenderId=i,this._childUpdateId+=1,this._isDirty=!1,this._position._isDirty=!1,this._rotation._isDirty=!1,this._scaling._isDirty=!1;const r=this._getEffectiveParent(),s=Si._TmpScaling;let a,o=this._position;if(this._infiniteDistance&&!this.parent&&t){const e=t.getWorldMatrix(),i=new B(e.m[12],e.m[13],e.m[14]);o=Si._TmpTranslation,o.copyFromFloats(this._position.x+i.x,this._position.y+i.y,this._position.z+i.z)}if(s.copyFromFloats(this._scaling.x*this.scalingDeterminant,this._scaling.y*this.scalingDeterminant,this._scaling.z*this.scalingDeterminant),this._rotationQuaternion){if(this._rotationQuaternion._isDirty=!1,a=this._rotationQuaternion,this.reIntegrateRotationIntoRotationQuaternion){this.rotation.lengthSquared()&&(this._rotationQuaternion.multiplyInPlace(V.RotationYawPitchRoll(this._rotation.y,this._rotation.x,this._rotation.z)),this._rotation.copyFromFloats(0,0,0))}}else a=Si._TmpRotation,V.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,a);if(this._usePivotMatrix){const e=H.Matrix[1];k.ScalingToRef(s.x,s.y,s.z,e);const t=H.Matrix[0];a.toRotationMatrix(t),this._pivotMatrix.multiplyToRef(e,H.Matrix[4]),H.Matrix[4].multiplyToRef(t,this._localMatrix),this._postMultiplyPivotMatrix&&this._localMatrix.multiplyToRef(this._pivotMatrixInverse,this._localMatrix),this._localMatrix.addTranslationFromFloats(o.x,o.y,o.z)}else k.ComposeToRef(s,a,o,this._localMatrix);if(r&&r.getWorldMatrix){if(e&&r.computeWorldMatrix(e),n.useBillboardPath){if(this._transformToBoneReferal){const e=this.parent;e.getSkeleton().prepare(),e.getFinalMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),H.Matrix[7])}else H.Matrix[7].copyFrom(r.getWorldMatrix());const e=H.Vector3[5],t=H.Vector3[6],i=H.Quaternion[0];H.Matrix[7].decompose(t,i,e),k.ScalingToRef(t.x,t.y,t.z,H.Matrix[7]),H.Matrix[7].setTranslation(e),Si.BillboardUseParentOrientation&&(this._position.applyRotationQuaternionToRef(i,e),this._localMatrix.setTranslation(e)),this._localMatrix.multiplyToRef(H.Matrix[7],this._worldMatrix)}else if(this._transformToBoneReferal){const e=this.parent;e.getSkeleton().prepare(),this._localMatrix.multiplyToRef(e.getFinalMatrix(),H.Matrix[6]),H.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),this._worldMatrix)}else this._localMatrix.multiplyToRef(r.getWorldMatrix(),this._worldMatrix);this._markSyncedWithParent()}else this._worldMatrix.copyFrom(this._localMatrix);if(n.useBillboardPath&&t&&this.billboardMode&&!n.useBillboardPosition){const e=H.Vector3[0];if(this._worldMatrix.getTranslationToRef(e),H.Matrix[1].copyFrom(t.getViewMatrix()),this._scene.useRightHandedSystem&&H.Matrix[1].multiplyToRef(Ri,H.Matrix[1]),H.Matrix[1].setTranslationFromFloats(0,0,0),H.Matrix[1].invertToRef(H.Matrix[0]),(this.billboardMode&Si.BILLBOARDMODE_ALL)!==Si.BILLBOARDMODE_ALL){H.Matrix[0].decompose(void 0,H.Quaternion[0],void 0);const e=H.Vector3[1];H.Quaternion[0].toEulerAnglesToRef(e),(this.billboardMode&Si.BILLBOARDMODE_X)!==Si.BILLBOARDMODE_X&&(e.x=0),(this.billboardMode&Si.BILLBOARDMODE_Y)!==Si.BILLBOARDMODE_Y&&(e.y=0),(this.billboardMode&Si.BILLBOARDMODE_Z)!==Si.BILLBOARDMODE_Z&&(e.z=0),k.RotationYawPitchRollToRef(e.y,e.x,e.z,H.Matrix[0])}this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(H.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(H.Vector3[0])}else if(n.useBillboardPath&&t&&n.useBillboardPosition){const e=H.Vector3[0];this._worldMatrix.getTranslationToRef(e);const i=t.globalPosition;this._worldMatrix.invertToRef(H.Matrix[1]);const n=H.Vector3[1];B.TransformCoordinatesToRef(i,H.Matrix[1],n),n.normalize();const r=-Math.atan2(n.z,n.x)+Math.PI/2,s=Math.sqrt(n.x*n.x+n.z*n.z),a=-Math.atan2(n.y,s);if(V.RotationYawPitchRollToRef(r,a,0,H.Quaternion[0]),(this.billboardMode&Si.BILLBOARDMODE_ALL)!==Si.BILLBOARDMODE_ALL){const e=H.Vector3[1];H.Quaternion[0].toEulerAnglesToRef(e),(this.billboardMode&Si.BILLBOARDMODE_X)!==Si.BILLBOARDMODE_X&&(e.x=0),(this.billboardMode&Si.BILLBOARDMODE_Y)!==Si.BILLBOARDMODE_Y&&(e.y=0),(this.billboardMode&Si.BILLBOARDMODE_Z)!==Si.BILLBOARDMODE_Z&&(e.z=0),k.RotationYawPitchRollToRef(e.y,e.x,e.z,H.Matrix[0])}else k.FromQuaternionToRef(H.Quaternion[0],H.Matrix[0]);this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(H.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(H.Vector3[0])}return this.ignoreNonUniformScaling?this._updateNonUniformScalingState(!1):this._scaling.isNonUniformWithinEpsilon(1e-6)?this._updateNonUniformScalingState(!0):r&&r._nonUniformScaling?this._updateNonUniformScalingState(r._nonUniformScaling):this._updateNonUniformScalingState(!1),this._afterComputeWorldMatrix(),this._absolutePosition.copyFromFloats(this._worldMatrix.m[12],this._worldMatrix.m[13],this._worldMatrix.m[14]),this._isAbsoluteSynced=!1,this.onAfterWorldMatrixUpdateObservable.notifyObservers(this),this._poseMatrix||(this._poseMatrix=k.Invert(this._worldMatrix)),this._worldMatrixDeterminantIsDirty=!0,this._worldMatrix}resetLocalMatrix(e=!0){if(this.computeWorldMatrix(),e){const e=this.getChildren();for(let t=0;t<e.length;++t){const i=e[t];if(i){i.computeWorldMatrix();const e=H.Matrix[0];i._localMatrix.multiplyToRef(this._localMatrix,e);const t=H.Quaternion[0];e.decompose(i.scaling,t,i.position),i.rotationQuaternion?i.rotationQuaternion.copyFrom(t):t.toEulerAnglesToRef(i.rotation)}}}this.scaling.copyFromFloats(1,1,1),this.position.copyFromFloats(0,0,0),this.rotation.copyFromFloats(0,0,0),this.rotationQuaternion&&(this.rotationQuaternion=V.Identity()),this._worldMatrix=k.Identity()}_afterComputeWorldMatrix(){}registerAfterWorldMatrixUpdate(e){return this.onAfterWorldMatrixUpdateObservable.add(e),this}unregisterAfterWorldMatrixUpdate(e){return this.onAfterWorldMatrixUpdateObservable.removeCallback(e),this}getPositionInCameraSpace(e=null){return e||(e=this.getScene().activeCamera),B.TransformCoordinates(this.getAbsolutePosition(),e.getViewMatrix())}getDistanceToCamera(e=null){return e||(e=this.getScene().activeCamera),this.getAbsolutePosition().subtract(e.globalPosition).length()}clone(e,t,i){const n=re.Clone((()=>new Si(e,this.getScene())),this);if(n.name=e,n.id=e,t&&(n.parent=t),!i){const t=this.getDescendants(!0);for(let i=0;i<t.length;i++){const r=t[i];r.clone&&r.clone(e+"."+r.name,n)}}return n}serialize(e){const t=re.Serialize(this,e);return t.type=this.getClassName(),t.uniqueId=this.uniqueId,this.parent&&this.parent._serializeAsParent(t),t.localMatrix=this.getPivotMatrix().asArray(),t.isEnabled=this.isEnabled(),re.AppendSerializedAnimations(this,t),t.ranges=this.serializeAnimationRanges(),t}static Parse(e,t,i){const n=re.Parse((()=>new Si(e.name,t)),e,t,i);if(e.localMatrix?n.setPreTransformMatrix(k.FromArray(e.localMatrix)):e.pivotMatrix&&n.setPivotMatrix(k.FromArray(e.pivotMatrix)),n.setEnabled(e.isEnabled),n._waitingParsedUniqueId=e.uniqueId,void 0!==e.parentId&&(n._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(n._waitingParentInstanceIndex=e.parentInstanceIndex),e.animations){for(let t=0;t<e.animations.length;t++){const i=e.animations[t],r=x("BABYLON.Animation");r&&n.animations.push(r.Parse(i))}ae.ParseAnimationRanges(n,e,t)}return e.autoAnimate&&t.beginAnimation(n,e.autoAnimateFrom,e.autoAnimateTo,e.autoAnimateLoop,e.autoAnimateSpeed||1),n}getChildTransformNodes(e,t){const i=[];return this._getDescendants(i,e,(e=>(!t||t(e))&&e instanceof Si)),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 n=null,r=null;t&&(this.rotationQuaternion?(r=this.rotationQuaternion.clone(),this.rotationQuaternion.copyFromFloats(0,0,0,1)):this.rotation&&(n=this.rotation.clone(),this.rotation.copyFromFloats(0,0,0)));const s=this.getHierarchyBoundingVectors(e,i),a=s.max.subtract(s.min),o=Math.max(a.x,a.y,a.z);if(0===o)return this;const l=1/o;return this.scaling.scaleInPlace(l),t&&(this.rotationQuaternion&&r?this.rotationQuaternion.copyFrom(r):this.rotation&&n&&this.rotation.copyFrom(n)),this}_syncAbsoluteScalingAndRotation(){this._isAbsoluteSynced||(this._worldMatrix.decompose(this._absoluteScaling,this._absoluteRotationQuaternion),this._isAbsoluteSynced=!0)}}var Ii;Si.BILLBOARDMODE_NONE=0,Si.BILLBOARDMODE_X=1,Si.BILLBOARDMODE_Y=2,Si.BILLBOARDMODE_Z=4,Si.BILLBOARDMODE_ALL=7,Si.BILLBOARDMODE_USE_POSITION=128,Si.BillboardUseParentOrientation=!1,Si._TmpRotation=V.Zero(),Si._TmpScaling=B.Zero(),Si._TmpTranslation=B.Zero(),Si._LookAtVectorCache=new B(0,0,0),Si._RotationAxisCache=new V,e([h("position")],Si.prototype,"_position",void 0),e([h("rotation")],Si.prototype,"_rotation",void 0),e([(Ii="rotationQuaternion",r(10,Ii))],Si.prototype,"_rotationQuaternion",void 0),e([h("scaling")],Si.prototype,"_scaling",void 0),e([a("billboardMode")],Si.prototype,"_billboardMode",void 0),e([a()],Si.prototype,"scalingDeterminant",void 0),e([a("infiniteDistance")],Si.prototype,"_infiniteDistance",void 0),e([a()],Si.prototype,"ignoreNonUniformScaling",void 0),e([a()],Si.prototype,"reIntegrateRotationIntoRotationQuaternion",void 0);class Ci{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(si.NormalKind))return null;let i,n=this.pickedMesh.getIndices();0===n?.length&&(n=null);const r=H.Vector3[0],s=H.Vector3[1],a=H.Vector3[2];if(t){const e=this.pickedMesh.getVerticesData(si.NormalKind);let t=n?B.FromArrayToRef(e,3*n[3*this.faceId],r):r.copyFromFloats(e[3*this.faceId*3],e[3*this.faceId*3+1],e[3*this.faceId*3+2]),o=n?B.FromArrayToRef(e,3*n[3*this.faceId+1],s):s.copyFromFloats(e[3*(3*this.faceId+1)],e[3*(3*this.faceId+1)+1],e[3*(3*this.faceId+1)+2]),l=n?B.FromArrayToRef(e,3*n[3*this.faceId+2],a):a.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),o=o.scale(this.bv),l=l.scale(1-this.bu-this.bv),i=new B(t.x+o.x+l.x,t.y+o.y+l.y,t.z+o.z+l.z)}else{const e=this.pickedMesh.getVerticesData(si.PositionKind),t=n?B.FromArrayToRef(e,3*n[3*this.faceId],r):r.copyFromFloats(e[3*this.faceId*3],e[3*this.faceId*3+1],e[3*this.faceId*3+2]),o=n?B.FromArrayToRef(e,3*n[3*this.faceId+1],s):s.copyFromFloats(e[3*(3*this.faceId+1)],e[3*(3*this.faceId+1)+1],e[3*(3*this.faceId+1)+2]),l=n?B.FromArrayToRef(e,3*n[3*this.faceId+2],a):a.copyFromFloats(e[3*(3*this.faceId+2)],e[3*(3*this.faceId+2)+1],e[3*(3*this.faceId+2)+2]),c=t.subtract(o),h=l.subtract(o);i=B.Cross(c,h)}const o=(e,t)=>{let i=e.getWorldMatrix();e.nonUniformScaling&&(H.Matrix[0].copyFrom(i),i=H.Matrix[0],i.setTranslationFromFloats(0,0,0),i.invert(),i.transposeToRef(H.Matrix[1]),i=H.Matrix[1]),B.TransformNormalToRef(t,i,t)};if(e&&o(this.pickedMesh,i),this.ray){const t=H.Vector3[0].copyFrom(i);e||o(this.pickedMesh,t),B.Dot(t,this.ray.direction)>0&&i.negateInPlace()}return i.normalize(),i}getTextureCoordinates(e=si.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=U.FromArray(i,2*t[3*this.faceId]),r=U.FromArray(i,2*t[3*this.faceId+1]),s=U.FromArray(i,2*t[3*this.faceId+2]);return n=n.scale(this.bu),r=r.scale(this.bv),s=s.scale(1-this.bu-this.bv),new U(n.x+r.x+s.x,n.y+r.y+s.y)}}class Mi{constructor(){this.shaderLanguage=0}postProcessor(e,t,i,n,r){if(r.drawBuffersExtensionDisabled){const t=/#extension.+GL_EXT_draw_buffers.+(enable|require)/g;e=e.replace(t,"")}return e}}const xi=/(flat\s)?\s*varying\s*.*/;class bi{constructor(){this.shaderLanguage=0}attributeProcessor(e){return e.replace("attribute","in")}varyingCheck(e,t){return xi.test(e)}varyingProcessor(e,t){return e.replace("varying",t?"in":"out")}postProcessor(e,t,i){const n=-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,(n||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}}class yi extends ni{constructor(e){super(),this._buffer=e}get underlyingResource(){return this._buffer}}class Oi{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()}}class Di{}class Ni extends vt{get name(){return this._name}set name(e){this._name=e}get version(){return this._webGLVersion}static get ShadersRepository(){return dt.ShadersRepository}static set ShadersRepository(e){dt.ShadersRepository=e}get supportsUniformBuffers(){return this.webGLVersion>1&&!this.disableUniformBuffers}get needPOTTextures(){return this._webGLVersion<2||this.forcePOTTextures}get _supportsHardwareTextureRescaling(){return!1}set framebufferDimensionsObject(e){this._framebufferDimensionsObject=e}snapshotRenderingReset(){this.snapshotRendering=!1}constructor(e,t,i,n){if(i=i||{},super(t??i.antialias,i,n),this._name="WebGL",this.forcePOTTextures=!1,this.validateShaderPrograms=!1,this.disableUniformBuffers=!1,this._webGLVersion=1,this._vertexAttribArraysEnabled=[],this._uintIndicesCurrentlySet=!1,this._currentBoundBuffer=new Array,this._currentFramebuffer=null,this._dummyFramebuffer=null,this._currentBufferPointers=new Array,this._currentInstanceLocations=new Array,this._currentInstanceBuffers=new Array,this._vaoRecordInProgress=!1,this._mustWipeVertexAttributes=!1,this._nextFreeTextureSlots=new Array,this._maxSimultaneousTextures=0,this._maxMSAASamplesOverride=null,this._unpackFlipYCached=null,this.enableUnpackFlipYCached=!0,this._boundUniforms={},!e)return;let r=null;if(e.getContext){if(r=e,this._renderingCanvas=r,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 Ni.ExceptionList){const n=t.key,r=t.targets;if(new RegExp(n).test(e)){if(t.capture&&t.captureConstraint){const i=t.capture,n=t.captureConstraint,r=new RegExp(i).exec(e);if(r&&r.length>0){if(parseInt(r[r.length-1])>=n)continue}}for(const e of r)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,de.Warn("WebGL context lost."),this.onContextLostObservable.notifyObservers(this)},this._onContextRestored=()=>{this._restoreEngineAfterContextLost((()=>this._initGLContext()))},r.addEventListener("webglcontextlost",this._onContextLost,!1),r.addEventListener("webglcontextrestored",this._onContextRestored,!1),i.powerPreference=i.powerPreference||"high-performance"),this._badDesktopOS&&(i.xrCompatible=!1),!i.disableWebGL2Support)try{this._gl=r.getContext("webgl2",i)||r.getContext("experimental-webgl2",i),this._gl&&(this._webGLVersion=2,this._shaderPlatformName="WEBGL2",this._gl.deleteQuery||(this._webGLVersion=1,this._shaderPlatformName="WEBGL1"))}catch(e){}if(!this._gl){if(!r)throw new Error("The provided canvas is null or undefined.");try{this._gl=r.getContext("webgl",i)||r.getContext("experimental-webgl",i)}catch(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;e<this._caps.maxVertexAttribs;e++)this._currentBufferPointers[e]=new Di;this._shaderProcessor=this.webGLVersion>1?new bi:new Mi;const s=`Babylon.js v${Ni.Version}`;de.Log(s+` - ${this.description}`),this._renderingCanvas&&this._renderingCanvas.setAttribute&&this._renderingCanvas.setAttribute("data-engine",s);const a=it(this._gl);a.validateShaderPrograms=this.validateShaderPrograms,a.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);else{const e=this._gl.getExtension("WEBGL_draw_buffers");if(null!==e){this._caps.drawBuffersExtension=!0,this._gl.drawBuffers=e.drawBuffersWEBGL.bind(e),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})}this._caps.supportSRGBBuffers=this._caps.supportSRGBBuffers&&!(!this._creationOptions||!this._creationOptions.forceSRGBBufferSupportState)}this._depthCullingState.depthTest=!0,this._depthCullingState.depthFunc=this._gl.LEQUAL,this._depthCullingState.depthMask=!0,this._maxSimultaneousTextures=this._caps.maxCombinedTexturesImageUnits;for(let e=0;e<this._maxSimultaneousTextures;e++)this._nextFreeTextureSlots.push(e);"Mali-G72"===this._glRenderer&&(this._caps.disableMorphTargetTexture=!0)}_initFeatures(){this._features={forceBitmapOverHTMLImageElement:"undefined"==typeof HTMLImageElement,supportRenderAndCopyToLodForFloatTextures:1!==this._webGLVersion,supportDepthStencilTexture:1!==this._webGLVersion,supportShadowSamplers:1!==this._webGLVersion,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:1!==this._webGLVersion,trackUbosInFrame:!1,checkUbosContentBeforeUpload:!1,supportCSM:1!==this._webGLVersion,basisNeedsPOT:1===this._webGLVersion,support3DTextures:1!==this._webGLVersion,needTypeSuffixInShaderConstants:1!==this._webGLVersion,supportMSAA:1!==this._webGLVersion,supportSSAO2:1!==this._webGLVersion,supportExtendedTextureFormats:1!==this._webGLVersion,supportSwitchCaseInShader:1!==this._webGLVersion,supportSyncTextureRead:!0,needsInvertingBitmap:!0,useUBOBindingCache:!0,needShaderCodeInlining:!1,needToAlwaysBindUniformBuffers:!1,supportRenderPasses:!1,supportSpriteInstancing:!0,forceVertexBufferStrideAndOffsetMultiple4Bytes:!1,_checkNonFloatVertexBuffersDontRecreatePipelineContext:!1,_collectUbosUpdatedInFrame:!1}}get webGLVersion(){return this._webGLVersion}getClassName(){return"ThinEngine"}_prepareWorkingCanvas(){if(this._workingCanvas)return;this._workingCanvas=this.createCanvas(1,1);const e=this._workingCanvas.getContext("2d");e&&(this._workingContext=e)}getInfo(){return this.getGlInfo()}getGlInfo(){return{vendor:this._glVendor,renderer:this._glRenderer,version:this._glVersion}}extractDriverInfo(){const e=this.getGlInfo();return e&&e.renderer?e.renderer:""}getRenderWidth(e=!1){return!e&&this._currentRenderTarget?this._currentRenderTarget.width:this._framebufferDimensionsObject?this._framebufferDimensionsObject.framebufferWidth:this._gl.drawingBufferWidth}getRenderHeight(e=!1){return!e&&this._currentRenderTarget?this._currentRenderTarget.height:this._framebufferDimensionsObject?this._framebufferDimensionsObject.framebufferHeight:this._gl.drawingBufferHeight}clear(e,t,i,n=!1){const r=this.stencilStateComposer.useStencilGlobalOnly;this.stencilStateComposer.useStencilGlobalOnly=!0,this.applyStates(),this.stencilStateComposer.useStencilGlobalOnly=r;let s=0;if(t&&e){let t=!0;if(this._currentRenderTarget){const i=this._currentRenderTarget.texture?.format;if(i===Ze.TEXTUREFORMAT_RED_INTEGER||i===Ze.TEXTUREFORMAT_RG_INTEGER||i===Ze.TEXTUREFORMAT_RGB_INTEGER||i===Ze.TEXTUREFORMAT_RGBA_INTEGER){const i=this._currentRenderTarget.texture?.type;i===Ze.TEXTURETYPE_UNSIGNED_INTEGER||i===Ze.TEXTURETYPE_UNSIGNED_SHORT?(Ni._TempClearColorUint32[0]=255*e.r,Ni._TempClearColorUint32[1]=255*e.g,Ni._TempClearColorUint32[2]=255*e.b,Ni._TempClearColorUint32[3]=255*e.a,this._gl.clearBufferuiv(this._gl.COLOR,0,Ni._TempClearColorUint32),t=!1):(Ni._TempClearColorInt32[0]=255*e.r,Ni._TempClearColorInt32[1]=255*e.g,Ni._TempClearColorInt32[2]=255*e.b,Ni._TempClearColorInt32[3]=255*e.a,this._gl.clearBufferiv(this._gl.COLOR,0,Ni._TempClearColorInt32),t=!1)}}t&&(this._gl.clearColor(e.r,e.g,e.b,void 0!==e.a?e.a:1),s|=this._gl.COLOR_BUFFER_BIT)}i&&(this.useReverseDepthBuffer?(this._depthCullingState.depthFunc=this._gl.GEQUAL,this._gl.clearDepth(0)):this._gl.clearDepth(1),s|=this._gl.DEPTH_BUFFER_BIT),n&&(this._gl.clearStencil(0),s|=this._gl.STENCIL_BUFFER_BIT),this._gl.clear(s)}_viewport(e,t,i,n){e===this._viewportCached.x&&t===this._viewportCached.y&&i===this._viewportCached.z&&n===this._viewportCached.w||(this._viewportCached.x=e,this._viewportCached.y=t,this._viewportCached.z=i,this._viewportCached.w=n,this._gl.viewport(e,t,i,n))}endFrame(){super.endFrame(),this._badOS&&this.flushFramebuffer()}get performanceMonitor(){throw new Error("Not Supported by ThinEngine")}bindFramebuffer(e,t=0,i,n,r,s=0,a=0){const o=e;this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,this._bindUnboundFramebuffer(o._MSAAFramebuffer?o._MSAAFramebuffer:o._framebuffer);const l=this._gl;e.isMulti||(e.is2DArray||e.is3D?l.framebufferTextureLayer(l.FRAMEBUFFER,l.COLOR_ATTACHMENT0,e.texture._hardwareTexture?.underlyingResource,s,a):e.isCube?l.framebufferTexture2D(l.FRAMEBUFFER,l.COLOR_ATTACHMENT0,l.TEXTURE_CUBE_MAP_POSITIVE_X+t,e.texture._hardwareTexture?.underlyingResource,s):o._currentLOD!==s&&(l.framebufferTexture2D(l.FRAMEBUFFER,l.COLOR_ATTACHMENT0,l.TEXTURE_2D,e.texture._hardwareTexture?.underlyingResource,s),o._currentLOD=s));const c=e._depthStencilTexture;if(c){e.is3D&&(e.texture.width===c.width&&e.texture.height===c.height&&e.texture.depth===c.depth||de.Warn("Depth/Stencil attachment for 3D target must have same dimensions as color attachment"));const i=e._depthStencilTextureWithStencil?l.DEPTH_STENCIL_ATTACHMENT:l.DEPTH_ATTACHMENT;e.is2DArray||e.is3D?l.framebufferTextureLayer(l.FRAMEBUFFER,i,c._hardwareTexture?.underlyingResource,s,a):e.isCube?l.framebufferTexture2D(l.FRAMEBUFFER,i,l.TEXTURE_CUBE_MAP_POSITIVE_X+t,c._hardwareTexture?.underlyingResource,s):l.framebufferTexture2D(l.FRAMEBUFFER,i,l.TEXTURE_2D,c._hardwareTexture?.underlyingResource,s)}this._cachedViewport&&!r?this.setViewport(this._cachedViewport,i,n):(i||(i=e.width,s&&(i/=Math.pow(2,s))),n||(n=e.height,s&&(n/=Math.pow(2,s))),this._viewport(0,0,i,n)),this.wipeCaches()}setState(e,t=0,i,n=!1,r,s,a=0){(this._depthCullingState.cull!==e||i)&&(this._depthCullingState.cull=e);const o=this.cullBackFaces??r??1?this._gl.BACK:this._gl.FRONT;(this._depthCullingState.cullFace!==o||i)&&(this._depthCullingState.cullFace=o),this.setZOffset(t),this.setZOffsetUnits(a);const l=n?this._gl.CW:this._gl.CCW;(this._depthCullingState.frontFace!==l||i)&&(this._depthCullingState.frontFace=l),this._stencilStateComposer.stencilMaterial=s}_bindUnboundFramebuffer(e){this._currentFramebuffer!==e&&(this._gl.bindFramebuffer(this._gl.FRAMEBUFFER,e),this._currentFramebuffer=e)}_currentFrameBufferIsDefaultFrameBuffer(){return null===this._currentFramebuffer}generateMipmaps(e){const t=this._getTextureTarget(e);this._bindTextureDirectly(t,e,!0),this._gl.generateMipmap(t),this._bindTextureDirectly(t,null)}unBindFramebuffer(e,t=!1,i){const n=e;this._currentRenderTarget=null;const r=this._gl;if(n._MSAAFramebuffer){if(e.isMulti)return void this.unBindMultiColorAttachmentFramebuffer(e,t,i);r.bindFramebuffer(r.READ_FRAMEBUFFER,n._MSAAFramebuffer),r.bindFramebuffer(r.DRAW_FRAMEBUFFER,n._framebuffer),r.blitFramebuffer(0,0,e.width,e.height,0,0,e.width,e.height,r.COLOR_BUFFER_BIT,r.NEAREST)}!e.texture?.generateMipMaps||t||e.isCube||this.generateMipmaps(e.texture),i&&(n._MSAAFramebuffer&&this._bindUnboundFramebuffer(n._framebuffer),i()),this._bindUnboundFramebuffer(null)}flushFramebuffer(){this._gl.flush()}restoreDefaultFramebuffer(){this._currentRenderTarget?this.unBindFramebuffer(this._currentRenderTarget):this._bindUnboundFramebuffer(null),this._cachedViewport&&this.setViewport(this._cachedViewport),this.wipeCaches()}_resetVertexBufferBinding(){this.bindArrayBuffer(null),this._cachedVertexBuffers=null}createVertexBuffer(e,t,i){return this._createVertexBuffer(e,this._gl.STATIC_DRAW)}_createVertexBuffer(e,t){const i=this._gl.createBuffer();if(!i)throw new Error("Unable to create vertex buffer");const n=new yi(i);return this.bindArrayBuffer(n),"number"!=typeof e?e instanceof Array?(this._gl.bufferData(this._gl.ARRAY_BUFFER,new Float32Array(e),t),n.capacity=4*e.length):(this._gl.bufferData(this._gl.ARRAY_BUFFER,e,t),n.capacity=e.byteLength):(this._gl.bufferData(this._gl.ARRAY_BUFFER,new Uint8Array(e),t),n.capacity=e),this._resetVertexBufferBinding(),n.references=1,n}createDynamicVertexBuffer(e,t){return this._createVertexBuffer(e,this._gl.DYNAMIC_DRAW)}_resetIndexBufferBinding(){this.bindIndexBuffer(null),this._cachedIndexBuffer=null}createIndexBuffer(e,t,i){const n=this._gl.createBuffer(),r=new yi(n);if(!n)throw new Error("Unable to create index buffer");this.bindIndexBuffer(r);const s=this._normalizeIndexData(e);return this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER,s,t?this._gl.DYNAMIC_DRAW:this._gl.STATIC_DRAW),this._resetIndexBufferBinding(),r.references=1,r.is32Bits=4===s.BYTES_PER_ELEMENT,r}_normalizeIndexData(e){if(2===e.BYTES_PER_ELEMENT)return e;if(this._caps.uintIndices){if(e instanceof Uint32Array)return e;for(let t=0;t<e.length;t++)if(e[t]>=65535)return new Uint32Array(e);return new Uint16Array(e)}return new Uint16Array(e)}bindArrayBuffer(e){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this._bindBuffer(e,this._gl.ARRAY_BUFFER)}bindUniformBlock(e,t,i){const n=e.program,r=this._gl.getUniformBlockIndex(n,t);this._gl.uniformBlockBinding(n,r,i)}bindIndexBuffer(e){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this._bindBuffer(e,this._gl.ELEMENT_ARRAY_BUFFER)}_bindBuffer(e,t){(this._vaoRecordInProgress||this._currentBoundBuffer[t]!==e)&&(this._gl.bindBuffer(t,e?e.underlyingResource:null),this._currentBoundBuffer[t]=e)}updateArrayBuffer(e){this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,e)}_vertexAttribPointer(e,t,i,n,r,s,a){const o=this._currentBufferPointers[t];if(!o)return;let l=!1;o.active?(o.buffer!==e&&(o.buffer=e,l=!0),o.size!==i&&(o.size=i,l=!0),o.type!==n&&(o.type=n,l=!0),o.normalized!==r&&(o.normalized=r,l=!0),o.stride!==s&&(o.stride=s,l=!0),o.offset!==a&&(o.offset=a,l=!0)):(l=!0,o.active=!0,o.index=t,o.size=i,o.type=n,o.normalized=r,o.stride=s,o.offset=a,o.buffer=e),(l||this._vaoRecordInProgress)&&(this.bindArrayBuffer(e),n===this._gl.UNSIGNED_INT||n===this._gl.INT?this._gl.vertexAttribIPointer(t,i,n,s,a):this._gl.vertexAttribPointer(t,i,n,r,s,a))}_bindIndexBufferWithCache(e){null!=e&&this._cachedIndexBuffer!==e&&(this._cachedIndexBuffer=e,this.bindIndexBuffer(e),this._uintIndicesCurrentlySet=e.is32Bits)}_bindVertexBuffersAttributes(e,t,i){const n=t.getAttributesNames();this._vaoRecordInProgress||this._unbindVertexArrayObject(),this.unbindAllAttributes();for(let r=0;r<n.length;r++){const s=t.getAttributeLocation(r);if(s>=0){const t=n[r];let a=null;if(i&&(a=i[t]),a||(a=e[t]),!a)continue;this._gl.enableVertexAttribArray(s),this._vaoRecordInProgress||(this._vertexAttribArraysEnabled[s]=!0);const o=a.getBuffer();o&&(this._vertexAttribPointer(o,s,a.getSize(),a.type,a.normalized,a.byteStride,a.byteOffset),a.getIsInstanced()&&(this._gl.vertexAttribDivisor(s,a.getInstanceDivisor()),this._vaoRecordInProgress||(this._currentInstanceLocations.push(s),this._currentInstanceBuffers.push(o))))}}}recordVertexArrayObject(e,t,i,n){const r=this._gl.createVertexArray();if(!r)throw new Error("Unable to create VAO");return this._vaoRecordInProgress=!0,this._gl.bindVertexArray(r),this._mustWipeVertexAttributes=!0,this._bindVertexBuffersAttributes(e,i,n),this.bindIndexBuffer(t),this._vaoRecordInProgress=!1,this._gl.bindVertexArray(null),r}bindVertexArrayObject(e,t){this._cachedVertexArrayObject!==e&&(this._cachedVertexArrayObject=e,this._gl.bindVertexArray(e),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._uintIndicesCurrentlySet=null!=t&&t.is32Bits,this._mustWipeVertexAttributes=!0)}bindBuffersDirectly(e,t,i,n,r){if(this._cachedVertexBuffers!==e||this._cachedEffectForVertexBuffers!==r){this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=r;const t=r.getAttributesCount();this._unbindVertexArrayObject(),this.unbindAllAttributes();let s=0;for(let a=0;a<t;a++)if(a<i.length){const t=r.getAttributeLocation(a);t>=0&&(this._gl.enableVertexAttribArray(t),this._vertexAttribArraysEnabled[t]=!0,this._vertexAttribPointer(e,t,i[a],this._gl.FLOAT,!1,n,s)),s+=4*i[a]}}this._bindIndexBufferWithCache(t)}_unbindVertexArrayObject(){this._cachedVertexArrayObject&&(this._cachedVertexArrayObject=null,this._gl.bindVertexArray(null))}bindBuffers(e,t,i,n){this._cachedVertexBuffers===e&&this._cachedEffectForVertexBuffers===i||(this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=i,this._bindVertexBuffersAttributes(e,i,n)),this._bindIndexBufferWithCache(t)}unbindInstanceAttributes(){let e;for(let t=0,i=this._currentInstanceLocations.length;t<i;t++){const i=this._currentInstanceBuffers[t];e!=i&&i.references&&(e=i,this.bindArrayBuffer(i));const n=this._currentInstanceLocations[t];this._gl.vertexAttribDivisor(n,0)}this._currentInstanceBuffers.length=0,this._currentInstanceLocations.length=0}releaseVertexArrayObject(e){this._gl.deleteVertexArray(e)}_releaseBuffer(e){return e.references--,0===e.references&&(this._deleteBuffer(e),!0)}_deleteBuffer(e){this._gl.deleteBuffer(e.underlyingResource)}updateAndBindInstancesBuffer(e,t,i){if(this.bindArrayBuffer(e),t&&this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,t),void 0!==i[0].index)this.bindInstancesBuffer(e,i,!0);else for(let t=0;t<4;t++){const n=i[t];this._vertexAttribArraysEnabled[n]||(this._gl.enableVertexAttribArray(n),this._vertexAttribArraysEnabled[n]=!0),this._vertexAttribPointer(e,n,4,this._gl.FLOAT,!1,64,16*t),this._gl.vertexAttribDivisor(n,1),this._currentInstanceLocations.push(n),this._currentInstanceBuffers.push(e)}}bindInstancesBuffer(e,t,i=!0){this.bindArrayBuffer(e);let n=0;if(i)for(let e=0;e<t.length;e++){n+=4*t[e].attributeSize}for(let i=0;i<t.length;i++){const r=t[i];void 0===r.index&&(r.index=this._currentEffect.getAttributeLocationByName(r.attributeName)),r.index<0||(this._vertexAttribArraysEnabled[r.index]||(this._gl.enableVertexAttribArray(r.index),this._vertexAttribArraysEnabled[r.index]=!0),this._vertexAttribPointer(e,r.index,r.attributeSize,r.attributeType||this._gl.FLOAT,r.normalized||!1,n,r.offset),this._gl.vertexAttribDivisor(r.index,void 0===r.divisor?1:r.divisor),this._currentInstanceLocations.push(r.index),this._currentInstanceBuffers.push(e))}}disableInstanceAttributeByName(e){if(!this._currentEffect)return;const t=this._currentEffect.getAttributeLocationByName(e);this.disableInstanceAttribute(t)}disableInstanceAttribute(e){let t,i=!1;for(;-1!==(t=this._currentInstanceLocations.indexOf(e));)this._currentInstanceLocations.splice(t,1),this._currentInstanceBuffers.splice(t,1),i=!0,t=this._currentInstanceLocations.indexOf(e);i&&(this._gl.vertexAttribDivisor(e,0),this.disableAttributeByIndex(e))}disableAttributeByIndex(e){this._gl.disableVertexAttribArray(e),this._vertexAttribArraysEnabled[e]=!1,this._currentBufferPointers[e].active=!1}draw(e,t,i,n){this.drawElementsType(e?Ze.MATERIAL_TriangleFillMode:Ze.MATERIAL_WireFrameFillMode,t,i,n)}drawPointClouds(e,t,i){this.drawArraysType(Ze.MATERIAL_PointFillMode,e,t,i)}drawUnIndexed(e,t,i,n){this.drawArraysType(e?Ze.MATERIAL_TriangleFillMode:Ze.MATERIAL_WireFrameFillMode,t,i,n)}drawElementsType(e,t,i,n){this.applyStates(),this._reportDrawCall();const r=this._drawMode(e),s=this._uintIndicesCurrentlySet?this._gl.UNSIGNED_INT:this._gl.UNSIGNED_SHORT,a=this._uintIndicesCurrentlySet?4:2;n?this._gl.drawElementsInstanced(r,i,s,t*a,n):this._gl.drawElements(r,i,s,t*a)}drawArraysType(e,t,i,n){this.applyStates(),this._reportDrawCall();const r=this._drawMode(e);n?this._gl.drawArraysInstanced(r,t,i,n):this._gl.drawArrays(r,t,i)}_drawMode(e){switch(e){case Ze.MATERIAL_TriangleFillMode:return this._gl.TRIANGLES;case Ze.MATERIAL_PointFillMode:return this._gl.POINTS;case Ze.MATERIAL_WireFrameFillMode:return this._gl.LINES;case Ze.MATERIAL_PointListDrawMode:return this._gl.POINTS;case Ze.MATERIAL_LineListDrawMode:return this._gl.LINES;case Ze.MATERIAL_LineLoopDrawMode:return this._gl.LINE_LOOP;case Ze.MATERIAL_LineStripDrawMode:return this._gl.LINE_STRIP;case Ze.MATERIAL_TriangleStripDrawMode:return this._gl.TRIANGLE_STRIP;case Ze.MATERIAL_TriangleFanDrawMode:return this._gl.TRIANGLE_FAN;default:return this._gl.TRIANGLES}}_releaseEffect(e){this._compiledEffects[e._key]&&delete this._compiledEffects[e._key];const t=e.getPipelineContext();t&&this._deletePipelineContext(t)}_deletePipelineContext(e){const t=e;t&&t.program&&(t.program.__SPECTOR_rebuildProgram=null,ct(t),this._gl.deleteProgram(t.program))}_getGlobalDefines(e){return Le(e,this.isNDCHalfZRange,this.useReverseDepthBuffer,this.useExactSrgbConversions)}createEffect(e,t,i,n,r,s,a,o,l,c=0,h){const d="string"==typeof e?e:e.vertexToken||e.vertexSource||e.vertexElement||e.vertex,u="string"==typeof e?e:e.fragmentToken||e.fragmentSource||e.fragmentElement||e.fragment,f=this._getGlobalDefines();let _=r??t.defines??"";f&&(_+=f);const m=d+"+"+u+"@"+_;if(this._compiledEffects[m]){const e=this._compiledEffects[m];return a&&e.isReady()&&a(e),e._refCount++,e}this._gl&&it(this._gl);const p=new dt(e,t,i,n,this,r,s,a,o,l,m,t.shaderLanguage??c,t.extraInitializationsAsync??h);return this._compiledEffects[m]=p,p}_getShaderSource(e){return this._gl.getShaderSource(e)}createRawShaderProgram(e,t,i,n,r=null){const s=it(this._gl);return s._contextWasLost=this._contextWasLost,s.validateShaderPrograms=this.validateShaderPrograms,nt(e,t,i,n||this._gl,r)}createShaderProgram(e,t,i,n,r,s=null){const a=it(this._gl);return a._contextWasLost=this._contextWasLost,a.validateShaderPrograms=this.validateShaderPrograms,rt(e,t,i,n,r||this._gl,s)}inlineShaderCode(e){return e}createPipelineContext(e){if(this._gl){it(this._gl).parallelShaderCompile=this._caps.parallelShaderCompile}const t=function(e){const t=new $e,i=it(e);return i.parallelShaderCompile&&(t.isParallelCompiled=!0),t.context=i._context,t}(this._gl);return t.engine=this,t}createMaterialContext(){}createDrawContext(){}_finalizePipelineContext(e){return at(e,this._gl,this.validateShaderPrograms)}_preparePipelineContext(e,t,i,n,r,s,a,o,l,c,h){const d=it(this._gl);return d._contextWasLost=this._contextWasLost,d.validateShaderPrograms=this.validateShaderPrograms,d._createShaderProgramInjection=this._createShaderProgram.bind(this),d.createRawShaderProgramInjection=this.createRawShaderProgram.bind(this),d.createShaderProgramInjection=this.createShaderProgram.bind(this),d.loadFileInjection=this._loadFile.bind(this),function(e,t,i,n,r,s,a,o,l,c="",h,d,u){const f=it(e.context);d||(d=f.createRawShaderProgramInjection??nt),u||(u=f.createShaderProgramInjection??rt);const _=e;_.program=n?d(_,t,i,_.context,l):u(_,t,i,o,_.context,l),_.program.__SPECTOR_rebuildProgram=a,h()}(e,t,i,n,0,0,a,o,l,c,h)}_createShaderProgram(e,t,i,n,r=null){return st(e,t,i,n,r)}_isRenderingStateCompiled(e){const t=e;return!this._isDisposed&&!t._isDisposed&&(!!this._gl.getProgramParameter(t.program,this._caps.parallelShaderCompile.COMPLETION_STATUS_KHR)&&(this._finalizePipelineContext(t),!0))}_executeWhenRenderingStateIsCompiled(e,t){!function(e,t){const i=e;if(!i.isParallelCompiled)return void t(e);const n=i.onCompiled;i.onCompiled=()=>{n?.(),t(e)}}(e,t)}getUniforms(e,t){const i=new Array,n=e;for(let e=0;e<t.length;e++)i.push(this._gl.getUniformLocation(n.program,t[e]));return i}getAttributes(e,t){const i=[],n=e;for(let e=0;e<t.length;e++)try{i.push(this._gl.getAttribLocation(n.program,t[e]))}catch(e){i.push(-1)}return i}enableEffect(e){(e=null!==e&&function(e){return void 0===e.getPipelineContext}(e)?e.effect:e)&&e!==this._currentEffect&&(this._stencilStateComposer.stencilMaterial=void 0,this.bindSamplers(e),this._currentEffect=e,e.onBind&&e.onBind(e),e._onBindObservable&&e._onBindObservable.notifyObservers(e))}setInt(e,t){return!!e&&(this._gl.uniform1i(e,t),!0)}setInt2(e,t,i){return!!e&&(this._gl.uniform2i(e,t,i),!0)}setInt3(e,t,i,n){return!!e&&(this._gl.uniform3i(e,t,i,n),!0)}setInt4(e,t,i,n,r){return!!e&&(this._gl.uniform4i(e,t,i,n,r),!0)}setIntArray(e,t){return!!e&&(this._gl.uniform1iv(e,t),!0)}setIntArray2(e,t){return!(!e||t.length%2!=0)&&(this._gl.uniform2iv(e,t),!0)}setIntArray3(e,t){return!(!e||t.length%3!=0)&&(this._gl.uniform3iv(e,t),!0)}setIntArray4(e,t){return!(!e||t.length%4!=0)&&(this._gl.uniform4iv(e,t),!0)}setUInt(e,t){return!!e&&(this._gl.uniform1ui(e,t),!0)}setUInt2(e,t,i){return!!e&&(this._gl.uniform2ui(e,t,i),!0)}setUInt3(e,t,i,n){return!!e&&(this._gl.uniform3ui(e,t,i,n),!0)}setUInt4(e,t,i,n,r){return!!e&&(this._gl.uniform4ui(e,t,i,n,r),!0)}setUIntArray(e,t){return!!e&&(this._gl.uniform1uiv(e,t),!0)}setUIntArray2(e,t){return!(!e||t.length%2!=0)&&(this._gl.uniform2uiv(e,t),!0)}setUIntArray3(e,t){return!(!e||t.length%3!=0)&&(this._gl.uniform3uiv(e,t),!0)}setUIntArray4(e,t){return!(!e||t.length%4!=0)&&(this._gl.uniform4uiv(e,t),!0)}setArray(e,t){return!!e&&(!(t.length<1)&&(this._gl.uniform1fv(e,t),!0))}setArray2(e,t){return!(!e||t.length%2!=0)&&(this._gl.uniform2fv(e,t),!0)}setArray3(e,t){return!(!e||t.length%3!=0)&&(this._gl.uniform3fv(e,t),!0)}setArray4(e,t){return!(!e||t.length%4!=0)&&(this._gl.uniform4fv(e,t),!0)}setMatrices(e,t){return!!e&&(this._gl.uniformMatrix4fv(e,!1,t),!0)}setMatrix3x3(e,t){return!!e&&(this._gl.uniformMatrix3fv(e,!1,t),!0)}setMatrix2x2(e,t){return!!e&&(this._gl.uniformMatrix2fv(e,!1,t),!0)}setFloat(e,t){return!!e&&(this._gl.uniform1f(e,t),!0)}setFloat2(e,t,i){return!!e&&(this._gl.uniform2f(e,t,i),!0)}setFloat3(e,t,i,n){return!!e&&(this._gl.uniform3f(e,t,i,n),!0)}setFloat4(e,t,i,n,r){return!!e&&(this._gl.uniform4f(e,t,i,n,r),!0)}applyStates(){if(this._depthCullingState.apply(this._gl),this._stencilStateComposer.apply(this._gl),this._alphaState.apply(this._gl),this._colorWriteChanged){this._colorWriteChanged=!1;const e=this._colorWrite;this._gl.colorMask(e,e,e,e)}}wipeCaches(e){this.preventCacheWipeBetweenFrames&&!e||(this._currentEffect=null,this._viewportCached.x=0,this._viewportCached.y=0,this._viewportCached.z=0,this._viewportCached.w=0,this._unbindVertexArrayObject(),e&&(this._currentProgram=null,this.resetTextureCache(),this._stencilStateComposer.reset(),this._depthCullingState.reset(),this._depthCullingState.depthFunc=this._gl.LEQUAL,this._alphaState.reset(),this._alphaMode=Ze.ALPHA_ADD,this._alphaEquation=Ze.ALPHA_DISABLE,this._colorWrite=!0,this._colorWriteChanged=!0,this._unpackFlipYCached=null,this._gl.pixelStorei(this._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL,this._gl.NONE),this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),this._mustWipeVertexAttributes=!0,this.unbindAllAttributes()),this._resetVertexBufferBinding(),this._cachedIndexBuffer=null,this._cachedEffectForVertexBuffers=null,this.bindIndexBuffer(null))}_getSamplingParameters(e,t){const i=this._gl;let n=i.NEAREST,r=i.NEAREST;switch(e){case Ze.TEXTURE_LINEAR_LINEAR_MIPNEAREST:n=i.LINEAR,r=t?i.LINEAR_MIPMAP_NEAREST:i.LINEAR;break;case Ze.TEXTURE_LINEAR_LINEAR_MIPLINEAR:n=i.LINEAR,r=t?i.LINEAR_MIPMAP_LINEAR:i.LINEAR;break;case Ze.TEXTURE_NEAREST_NEAREST_MIPLINEAR:n=i.NEAREST,r=t?i.NEAREST_MIPMAP_LINEAR:i.NEAREST;break;case Ze.TEXTURE_NEAREST_NEAREST_MIPNEAREST:n=i.NEAREST,r=t?i.NEAREST_MIPMAP_NEAREST:i.NEAREST;break;case Ze.TEXTURE_NEAREST_LINEAR_MIPNEAREST:n=i.NEAREST,r=t?i.LINEAR_MIPMAP_NEAREST:i.LINEAR;break;case Ze.TEXTURE_NEAREST_LINEAR_MIPLINEAR:n=i.NEAREST,r=t?i.LINEAR_MIPMAP_LINEAR:i.LINEAR;break;case Ze.TEXTURE_NEAREST_LINEAR:n=i.NEAREST,r=i.LINEAR;break;case Ze.TEXTURE_NEAREST_NEAREST:n=i.NEAREST,r=i.NEAREST;break;case Ze.TEXTURE_LINEAR_NEAREST_MIPNEAREST:n=i.LINEAR,r=t?i.NEAREST_MIPMAP_NEAREST:i.NEAREST;break;case Ze.TEXTURE_LINEAR_NEAREST_MIPLINEAR:n=i.LINEAR,r=t?i.NEAREST_MIPMAP_LINEAR:i.NEAREST;break;case Ze.TEXTURE_LINEAR_LINEAR:n=i.LINEAR,r=i.LINEAR;break;case Ze.TEXTURE_LINEAR_NEAREST:n=i.LINEAR,r=i.NEAREST}return{min:r,mag:n}}_createTexture(){const e=this._gl.createTexture();if(!e)throw new Error("Unable to create texture");return e}_createHardwareTexture(){return new Oi(this._createTexture(),this._gl)}_createInternalTexture(e,t,i=!0,n=0){let r,s=!1,a=Ze.TEXTURETYPE_UNSIGNED_INT,o=Ze.TEXTURE_TRILINEAR_SAMPLINGMODE,l=Ze.TEXTUREFORMAT_RGBA,c=!1,h=1;void 0!==t&&"object"==typeof t?(s=!!t.generateMipMaps,a=void 0===t.type?Ze.TEXTURETYPE_UNSIGNED_INT:t.type,o=void 0===t.samplingMode?Ze.TEXTURE_TRILINEAR_SAMPLINGMODE:t.samplingMode,l=void 0===t.format?Ze.TEXTUREFORMAT_RGBA:t.format,c=void 0!==t.useSRGBBuffer&&t.useSRGBBuffer,h=t.samples??1,r=t.label):s=!!t,c&&=this._caps.supportSRGBBuffers&&(this.webGLVersion>1||this.isWebGPU),(a!==Ze.TEXTURETYPE_FLOAT||this._caps.textureFloatLinearFiltering)&&(a!==Ze.TEXTURETYPE_HALF_FLOAT||this._caps.textureHalfFloatLinearFiltering)||(o=Ze.TEXTURE_NEAREST_SAMPLINGMODE),a!==Ze.TEXTURETYPE_FLOAT||this._caps.textureFloat||(a=Ze.TEXTURETYPE_UNSIGNED_INT,de.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));const d=this._gl,u=new Et(this,n),f=e.width||e,_=e.height||e,m=e.depth||0,p=e.layers||0,g=this._getSamplingParameters(o,s),E=0!==p?d.TEXTURE_2D_ARRAY:0!==m?d.TEXTURE_3D:d.TEXTURE_2D,T=this._getRGBABufferInternalSizedFormat(a,l,c),A=this._getInternalFormat(l),v=this._getWebGLTextureType(a);return this._bindTextureDirectly(E,u),0!==p?(u.is2DArray=!0,d.texImage3D(E,0,T,f,_,p,0,A,v,null)):0!==m?(u.is3D=!0,d.texImage3D(E,0,T,f,_,m,0,A,v,null)):d.texImage2D(E,0,T,f,_,0,A,v,null),d.texParameteri(E,d.TEXTURE_MAG_FILTER,g.mag),d.texParameteri(E,d.TEXTURE_MIN_FILTER,g.min),d.texParameteri(E,d.TEXTURE_WRAP_S,d.CLAMP_TO_EDGE),d.texParameteri(E,d.TEXTURE_WRAP_T,d.CLAMP_TO_EDGE),s&&this._gl.generateMipmap(E),this._bindTextureDirectly(E,null),u._useSRGBBuffer=c,u.baseWidth=f,u.baseHeight=_,u.width=f,u.height=_,u.depth=p,u.isReady=!0,u.samples=h,u.generateMipMaps=s,u.samplingMode=o,u.type=a,u.format=l,u.label=r,this._internalTexturesCache.push(u),u}_getUseSRGBBuffer(e,t){return e&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||t)}createTexture(e,t,i,n,r=Ze.TEXTURE_TRILINEAR_SAMPLINGMODE,s=null,a=null,o=null,l=null,c=null,h=null,d,u,f,_){return this._createTextureBase(e,t,i,n,r,s,a,((...e)=>this._prepareWebGLTexture(...e,c)),((e,t,i,r,s,a)=>{const o=this._gl,l=i.width===e&&i.height===t;s._creationFlags=f??0;const c=this._getTexImageParametersForCreateTexture(s.format,s._useSRGBBuffer);if(l)return o.texImage2D(o.TEXTURE_2D,0,c.internalFormat,c.format,c.type,i),!1;const h=this._caps.maxTextureSize;if(i.width>h||i.height>h||!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),o.texImage2D(o.TEXTURE_2D,0,c.internalFormat,c.format,c.type,this._workingCanvas),s.width=e,s.height=t,!1);{const e=new Et(this,2);this._bindTextureDirectly(o.TEXTURE_2D,e,!0),o.texImage2D(o.TEXTURE_2D,0,c.internalFormat,c.format,c.type,i),this._rescaleTexture(e,s,n,c.format,(()=>{this._releaseTexture(e),this._bindTextureDirectly(o.TEXTURE_2D,s,!0),a()}))}return!0}),o,l,c,h,d,u,_)}_getTexImageParametersForCreateTexture(e,t){let i,n;return 1===this.webGLVersion?(i=this._getInternalFormat(e,t),n=i):(i=this._getInternalFormat(e,!1),n=this._getRGBABufferInternalSizedFormat(Ze.TEXTURETYPE_UNSIGNED_BYTE,e,t)),{internalFormat:n,format:i,type:this._gl.UNSIGNED_BYTE}}_rescaleTexture(e,t,i,n,r){}_unpackFlipY(e){this._unpackFlipYCached!==e&&(this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL,e?1:0),this.enableUnpackFlipYCached&&(this._unpackFlipYCached=e))}_getUnpackAlignement(){return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT)}_getTextureTarget(e){return e.isCube?this._gl.TEXTURE_CUBE_MAP:e.is3D?this._gl.TEXTURE_3D:e.is2DArray||e.isMultiview?this._gl.TEXTURE_2D_ARRAY:this._gl.TEXTURE_2D}updateTextureSamplingMode(e,t,i=!1){const n=this._getTextureTarget(t),r=this._getSamplingParameters(e,t.useMipMaps||i);this._setTextureParameterInteger(n,this._gl.TEXTURE_MAG_FILTER,r.mag,t),this._setTextureParameterInteger(n,this._gl.TEXTURE_MIN_FILTER,r.min),i&&(t.generateMipMaps=!0,this._gl.generateMipmap(n)),this._bindTextureDirectly(n,null),t.samplingMode=e}updateTextureDimensions(e,t,i,n=1){}updateTextureWrappingMode(e,t,i=null,n=null){const r=this._getTextureTarget(e);null!==t&&(this._setTextureParameterInteger(r,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t),e),e._cachedWrapU=t),null!==i&&(this._setTextureParameterInteger(r,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(i),e),e._cachedWrapV=i),(e.is2DArray||e.is3D)&&null!==n&&(this._setTextureParameterInteger(r,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(n),e),e._cachedWrapR=n),this._bindTextureDirectly(r,null)}_uploadCompressedDataToTextureDirectly(e,t,i,n,r,s=0,a=0){const o=this._gl;let l=o.TEXTURE_2D;if(e.isCube&&(l=o.TEXTURE_CUBE_MAP_POSITIVE_X+s),e._useSRGBBuffer)switch(t){case Ze.TEXTUREFORMAT_COMPRESSED_RGB8_ETC2:case Ze.TEXTUREFORMAT_COMPRESSED_RGB_ETC1_WEBGL:this._caps.etc2?t=o.COMPRESSED_SRGB8_ETC2:e._useSRGBBuffer=!1;break;case Ze.TEXTUREFORMAT_COMPRESSED_RGBA8_ETC2_EAC:this._caps.etc2?t=o.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:e._useSRGBBuffer=!1;break;case Ze.TEXTUREFORMAT_COMPRESSED_RGBA_BPTC_UNORM:t=o.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT;break;case Ze.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_4x4:t=o.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR;break;case Ze.TEXTUREFORMAT_COMPRESSED_RGB_S3TC_DXT1:this._caps.s3tc_srgb?t=o.COMPRESSED_SRGB_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case Ze.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT1:this._caps.s3tc_srgb?t=o.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case Ze.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT5:this._caps.s3tc_srgb?t=o.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT:e._useSRGBBuffer=!1;break;default:e._useSRGBBuffer=!1}this._gl.compressedTexImage2D(l,a,t,i,n,0,r)}_uploadDataToTextureDirectly(e,t,i=0,n=0,r,s=!1){const a=this._gl,o=this._getWebGLTextureType(e.type),l=this._getInternalFormat(e.format),c=void 0===r?this._getRGBABufferInternalSizedFormat(e.type,e.format,e._useSRGBBuffer):this._getInternalFormat(r,e._useSRGBBuffer);this._unpackFlipY(e.invertY);let h=a.TEXTURE_2D;e.isCube&&(h=a.TEXTURE_CUBE_MAP_POSITIVE_X+i);const d=Math.round(Math.log(e.width)*Math.LOG2E),u=Math.round(Math.log(e.height)*Math.LOG2E),f=s?e.width:Math.pow(2,Math.max(d-n,0)),_=s?e.height:Math.pow(2,Math.max(u-n,0));a.texImage2D(h,n,c,f,_,0,l,o,t)}updateTextureData(e,t,i,n,r,s,a=0,o=0,l=!1){const c=this._gl,h=this._getWebGLTextureType(e.type),d=this._getInternalFormat(e.format);this._unpackFlipY(e.invertY);let u=c.TEXTURE_2D,f=c.TEXTURE_2D;e.isCube&&(f=c.TEXTURE_CUBE_MAP_POSITIVE_X+a,u=c.TEXTURE_CUBE_MAP),this._bindTextureDirectly(u,e,!0),c.texSubImage2D(f,o,i,n,r,s,d,h,t),l&&this._gl.generateMipmap(f),this._bindTextureDirectly(u,null)}_uploadArrayBufferViewToTexture(e,t,i=0,n=0){const r=this._gl,s=e.isCube?r.TEXTURE_CUBE_MAP:r.TEXTURE_2D;this._bindTextureDirectly(s,e,!0),this._uploadDataToTextureDirectly(e,t,i,n),this._bindTextureDirectly(s,null,!0)}_prepareWebGLTextureContinuation(e,t,i,n,r){const s=this._gl;if(!s)return;const a=this._getSamplingParameters(r,!i);s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,a.mag),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,a.min),i||n||s.generateMipmap(s.TEXTURE_2D),this._bindTextureDirectly(s.TEXTURE_2D,null),t&&t.removePendingData(e),e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear()}_prepareWebGLTexture(e,t,i,n,r,s,a,o,l,c){const h=this.getCaps().maxTextureSize,d=Math.min(h,this.needPOTTextures?zt(n.width,h):n.width),u=Math.min(h,this.needPOTTextures?zt(n.height,h):n.height),f=this._gl;f&&(e._hardwareTexture?(this._bindTextureDirectly(f.TEXTURE_2D,e,!0),this._unpackFlipY(void 0===r||!!r),e.baseWidth=n.width,e.baseHeight=n.height,e.width=d,e.height=u,e.isReady=!0,e.type=-1!==e.type?e.type:Ze.TEXTURETYPE_UNSIGNED_BYTE,e.format=-1!==e.format?e.format:c??(".jpg"!==t||e._useSRGBBuffer?Ze.TEXTUREFORMAT_RGBA:Ze.TEXTUREFORMAT_RGB),o(d,u,n,t,e,(()=>{this._prepareWebGLTextureContinuation(e,i,s,a,l)}))||this._prepareWebGLTextureContinuation(e,i,s,a,l)):i&&i.removePendingData(e))}_setupFramebufferDepthAttachments(e,t,i,n,r=1){const s=this._gl;if(e&&t)return this._createRenderBuffer(i,n,r,s.DEPTH_STENCIL,s.DEPTH24_STENCIL8,s.DEPTH_STENCIL_ATTACHMENT);if(t){let e=s.DEPTH_COMPONENT16;return this._webGLVersion>1&&(e=s.DEPTH_COMPONENT32F),this._createRenderBuffer(i,n,r,e,e,s.DEPTH_ATTACHMENT)}return e?this._createRenderBuffer(i,n,r,s.STENCIL_INDEX8,s.STENCIL_INDEX8,s.STENCIL_ATTACHMENT):null}_createRenderBuffer(e,t,i,n,r,s,a=!0){const o=this._gl.createRenderbuffer();return this._updateRenderBuffer(o,e,t,i,n,r,s,a)}_updateRenderBuffer(e,t,i,n,r,s,a,o=!0){const l=this._gl;return l.bindRenderbuffer(l.RENDERBUFFER,e),n>1&&l.renderbufferStorageMultisample?l.renderbufferStorageMultisample(l.RENDERBUFFER,n,s,t,i):l.renderbufferStorage(l.RENDERBUFFER,r,t,i),l.framebufferRenderbuffer(l.FRAMEBUFFER,a,l.RENDERBUFFER,e),o&&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&&(!function(e,t){t.useProgram(e)}(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<i.length;t++){const n=e.getUniform(i[t]);n&&(this._boundUniforms[t]=n)}this._currentEffect=null}_activateCurrentTexture(){this._currentTextureChannel!==this._activeChannel&&(this._gl.activeTexture(this._gl.TEXTURE0+this._activeChannel),this._currentTextureChannel=this._activeChannel)}_bindTextureDirectly(e,t,i=!1,n=!1){let r=!1;const s=t&&t._associatedChannel>-1;i&&s&&(this._activeChannel=t._associatedChannel);if(this._boundTexturesCache[this._activeChannel]!==t||n){if(this._activateCurrentTexture(),t&&t.isMultiview)throw de.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&&(r=!0,this._activateCurrentTexture());return s&&!i&&this._bindSamplerUniformToChannel(t._associatedChannel,this._activeChannel),r}_bindTexture(e,t,i){if(void 0===e)return;t&&(t._associatedChannel=e),this._activeChannel=e;const n=t?this._getTextureTarget(t):this._gl.TEXTURE_2D;this._bindTextureDirectly(n,t)}unbindAllTextures(){for(let e=0;e<this._maxSimultaneousTextures;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))}setTexture(e,t,i,n){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 Ze.TEXTURE_WRAP_ADDRESSMODE:return this._gl.REPEAT;case Ze.TEXTURE_CLAMP_ADDRESSMODE:return this._gl.CLAMP_TO_EDGE;case Ze.TEXTURE_MIRROR_ADDRESSMODE:return this._gl.MIRRORED_REPEAT}return this._gl.REPEAT}_setTexture(e,t,i=!1,n=!1,r=""){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(t.delayLoadState===Ze.DELAYLOADSTATE_NOTLOADED)return t.delayLoad(),!1;let s;s=n?t.depthStencilTexture:t.isReady()?t.getInternalTexture():t.isCube?this.emptyCubeTexture:t.is3D?this.emptyTexture3D:t.is2DArray?this.emptyTexture2DArray:this.emptyTexture,!i&&s&&(s._associatedChannel=e);let a=!0;this._boundTexturesCache[e]===s&&(i||this._bindSamplerUniformToChannel(s._associatedChannel,e),a=!1),this._activeChannel=e;const o=this._getTextureTarget(s);if(a&&this._bindTextureDirectly(o,s,i),s&&!s.isMultiview){if(s.isCube&&s._cachedCoordinatesMode!==t.coordinatesMode){s._cachedCoordinatesMode=t.coordinatesMode;const e=t.coordinatesMode!==Ze.TEXTURE_CUBIC_MODE&&t.coordinatesMode!==Ze.TEXTURE_SKYBOX_MODE?Ze.TEXTURE_WRAP_ADDRESSMODE:Ze.TEXTURE_CLAMP_ADDRESSMODE;t.wrapU=e,t.wrapV=e}s._cachedWrapU!==t.wrapU&&(s._cachedWrapU=t.wrapU,this._setTextureParameterInteger(o,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t.wrapU),s)),s._cachedWrapV!==t.wrapV&&(s._cachedWrapV=t.wrapV,this._setTextureParameterInteger(o,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(t.wrapV),s)),s.is3D&&s._cachedWrapR!==t.wrapR&&(s._cachedWrapR=t.wrapR,this._setTextureParameterInteger(o,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(t.wrapR),s)),this._setAnisotropicLevel(o,s,t.anisotropicFilteringLevel)}return!0}setTextureArray(e,t,i,n){if(void 0!==e&&t){this._textureUnits&&this._textureUnits.length===i.length||(this._textureUnits=new Int32Array(i.length));for(let t=0;t<i.length;t++){const n=i[t].getInternalTexture();n?(this._textureUnits[t]=e+t,n._associatedChannel=e+t):this._textureUnits[t]=-1}this._gl.uniform1iv(t,this._textureUnits);for(let e=0;e<i.length;e++)this._setTexture(this._textureUnits[e],i[e],!0)}}_setAnisotropicLevel(e,t,i){const n=this._caps.textureAnisotropicFilterExtension;t.samplingMode!==Ze.TEXTURE_LINEAR_LINEAR_MIPNEAREST&&t.samplingMode!==Ze.TEXTURE_LINEAR_LINEAR_MIPLINEAR&&t.samplingMode!==Ze.TEXTURE_LINEAR_LINEAR&&(i=1),n&&t._cachedAnisotropicFilteringLevel!==i&&(this._setTextureParameterFloat(e,n.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(i,this._caps.maxAnisotropy),t),t._cachedAnisotropicFilteringLevel=i)}_setTextureParameterFloat(e,t,i,n){this._bindTextureDirectly(e,n,!0,!0),this._gl.texParameterf(e,t,i)}_setTextureParameterInteger(e,t,i,n){n&&this._bindTextureDirectly(e,n,!0,!0),this._gl.texParameteri(e,t,i)}unbindAllAttributes(){if(this._mustWipeVertexAttributes){this._mustWipeVertexAttributes=!1;for(let e=0;e<this._caps.maxVertexAttribs;e++)this.disableAttributeByIndex(e)}else for(let e=0,t=this._vertexAttribArraysEnabled.length;e<t;e++)e>=this._caps.maxVertexAttribs||!this._vertexAttribArraysEnabled[e]||this.disableAttributeByIndex(e)}releaseEffects(){const e=Object.keys(this._compiledEffects);for(const t of e){this._compiledEffects[t].dispose()}this._compiledEffects={}}dispose(){var e;oe()&&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(),e=this._gl,et.delete(e)}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(Ze.TEXTURETYPE_FLOAT)}_canRenderToHalfFloatFramebuffer(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(Ze.TEXTURETYPE_HALF_FLOAT)}_canRenderToFramebuffer(e){const t=this._gl;for(;t.getError()!==t.NO_ERROR;);let i=!0;const n=t.createTexture();t.bindTexture(t.TEXTURE_2D,n),t.texImage2D(t.TEXTURE_2D,0,this._getRGBABufferInternalSizedFormat(e),1,1,0,t.RGBA,this._getWebGLTextureType(e),null),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST);const r=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,r),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,n,0);const s=t.checkFramebufferStatus(t.FRAMEBUFFER);if(i=i&&s===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,n=t.UNSIGNED_BYTE,r=new Uint8Array(4);t.readPixels(0,0,1,1,e,n,r),i=i&&t.getError()===t.NO_ERROR}for(t.deleteTexture(n),t.deleteFramebuffer(r),t.bindFramebuffer(t.FRAMEBUFFER,null);!i&&t.getError()!==t.NO_ERROR;);return i}_getWebGLTextureType(e){if(1===this._webGLVersion){switch(e){case Ze.TEXTURETYPE_FLOAT:return this._gl.FLOAT;case Ze.TEXTURETYPE_HALF_FLOAT:return this._gl.HALF_FLOAT_OES;case Ze.TEXTURETYPE_UNSIGNED_BYTE:return this._gl.UNSIGNED_BYTE;case Ze.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:return this._gl.UNSIGNED_SHORT_4_4_4_4;case Ze.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:return this._gl.UNSIGNED_SHORT_5_5_5_1;case Ze.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:return this._gl.UNSIGNED_SHORT_5_6_5}return this._gl.UNSIGNED_BYTE}switch(e){case Ze.TEXTURETYPE_BYTE:return this._gl.BYTE;case Ze.TEXTURETYPE_UNSIGNED_BYTE:return this._gl.UNSIGNED_BYTE;case Ze.TEXTURETYPE_SHORT:return this._gl.SHORT;case Ze.TEXTURETYPE_UNSIGNED_SHORT:return this._gl.UNSIGNED_SHORT;case Ze.TEXTURETYPE_INT:return this._gl.INT;case Ze.TEXTURETYPE_UNSIGNED_INTEGER:return this._gl.UNSIGNED_INT;case Ze.TEXTURETYPE_FLOAT:return this._gl.FLOAT;case Ze.TEXTURETYPE_HALF_FLOAT:return this._gl.HALF_FLOAT;case Ze.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:return this._gl.UNSIGNED_SHORT_4_4_4_4;case Ze.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:return this._gl.UNSIGNED_SHORT_5_5_5_1;case Ze.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:return this._gl.UNSIGNED_SHORT_5_6_5;case Ze.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:return this._gl.UNSIGNED_INT_2_10_10_10_REV;case Ze.TEXTURETYPE_UNSIGNED_INT_24_8:return this._gl.UNSIGNED_INT_24_8;case Ze.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:return this._gl.UNSIGNED_INT_10F_11F_11F_REV;case Ze.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:return this._gl.UNSIGNED_INT_5_9_9_9_REV;case Ze.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV: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 Ze.TEXTUREFORMAT_ALPHA:i=this._gl.ALPHA;break;case Ze.TEXTUREFORMAT_LUMINANCE:i=this._gl.LUMINANCE;break;case Ze.TEXTUREFORMAT_LUMINANCE_ALPHA:i=this._gl.LUMINANCE_ALPHA;break;case Ze.TEXTUREFORMAT_RED:i=this._gl.RED;break;case Ze.TEXTUREFORMAT_RG:i=this._gl.RG;break;case Ze.TEXTUREFORMAT_RGB:i=t?this._glSRGBExtensionValues.SRGB:this._gl.RGB;break;case Ze.TEXTUREFORMAT_RGBA:i=t?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA}if(this._webGLVersion>1)switch(e){case Ze.TEXTUREFORMAT_RED_INTEGER:i=this._gl.RED_INTEGER;break;case Ze.TEXTUREFORMAT_RG_INTEGER:i=this._gl.RG_INTEGER;break;case Ze.TEXTUREFORMAT_RGB_INTEGER:i=this._gl.RGB_INTEGER;break;case Ze.TEXTUREFORMAT_RGBA_INTEGER:i=this._gl.RGBA_INTEGER}return i}_getRGBABufferInternalSizedFormat(e,t,i=!1){if(1===this._webGLVersion){if(void 0!==t)switch(t){case Ze.TEXTUREFORMAT_ALPHA:return this._gl.ALPHA;case Ze.TEXTUREFORMAT_LUMINANCE:return this._gl.LUMINANCE;case Ze.TEXTUREFORMAT_LUMINANCE_ALPHA:return this._gl.LUMINANCE_ALPHA;case Ze.TEXTUREFORMAT_RGB:return i?this._glSRGBExtensionValues.SRGB:this._gl.RGB}return this._gl.RGBA}switch(e){case Ze.TEXTURETYPE_BYTE:switch(t){case Ze.TEXTUREFORMAT_RED:return this._gl.R8_SNORM;case Ze.TEXTUREFORMAT_RG:return this._gl.RG8_SNORM;case Ze.TEXTUREFORMAT_RGB:return this._gl.RGB8_SNORM;case Ze.TEXTUREFORMAT_RED_INTEGER:return this._gl.R8I;case Ze.TEXTUREFORMAT_RG_INTEGER:return this._gl.RG8I;case Ze.TEXTUREFORMAT_RGB_INTEGER:return this._gl.RGB8I;case Ze.TEXTUREFORMAT_RGBA_INTEGER:return this._gl.RGBA8I;default:return this._gl.RGBA8_SNORM}case Ze.TEXTURETYPE_UNSIGNED_BYTE:switch(t){case Ze.TEXTUREFORMAT_RED:return this._gl.R8;case Ze.TEXTUREFORMAT_RG:return this._gl.RG8;case Ze.TEXTUREFORMAT_RGB:return i?this._glSRGBExtensionValues.SRGB8:this._gl.RGB8;case Ze.TEXTUREFORMAT_RGBA:return i?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA8;case Ze.TEXTUREFORMAT_RED_INTEGER:return this._gl.R8UI;case Ze.TEXTUREFORMAT_RG_INTEGER:return this._gl.RG8UI;case Ze.TEXTUREFORMAT_RGB_INTEGER:return this._gl.RGB8UI;case Ze.TEXTUREFORMAT_RGBA_INTEGER:return this._gl.RGBA8UI;case Ze.TEXTUREFORMAT_ALPHA:return this._gl.ALPHA;case Ze.TEXTUREFORMAT_LUMINANCE:return this._gl.LUMINANCE;case Ze.TEXTUREFORMAT_LUMINANCE_ALPHA:return this._gl.LUMINANCE_ALPHA;default:return this._gl.RGBA8}case Ze.TEXTURETYPE_SHORT:switch(t){case Ze.TEXTUREFORMAT_RED_INTEGER:return this._gl.R16I;case Ze.TEXTUREFORMAT_RG_INTEGER:return this._gl.RG16I;case Ze.TEXTUREFORMAT_RGB_INTEGER:return this._gl.RGB16I;case Ze.TEXTUREFORMAT_RGBA_INTEGER:default:return this._gl.RGBA16I}case Ze.TEXTURETYPE_UNSIGNED_SHORT:switch(t){case Ze.TEXTUREFORMAT_RED_INTEGER:return this._gl.R16UI;case Ze.TEXTUREFORMAT_RG_INTEGER:return this._gl.RG16UI;case Ze.TEXTUREFORMAT_RGB_INTEGER:return this._gl.RGB16UI;case Ze.TEXTUREFORMAT_RGBA_INTEGER:default:return this._gl.RGBA16UI}case Ze.TEXTURETYPE_INT:switch(t){case Ze.TEXTUREFORMAT_RED_INTEGER:return this._gl.R32I;case Ze.TEXTUREFORMAT_RG_INTEGER:return this._gl.RG32I;case Ze.TEXTUREFORMAT_RGB_INTEGER:return this._gl.RGB32I;case Ze.TEXTUREFORMAT_RGBA_INTEGER:default:return this._gl.RGBA32I}case Ze.TEXTURETYPE_UNSIGNED_INTEGER:switch(t){case Ze.TEXTUREFORMAT_RED_INTEGER:return this._gl.R32UI;case Ze.TEXTUREFORMAT_RG_INTEGER:return this._gl.RG32UI;case Ze.TEXTUREFORMAT_RGB_INTEGER:return this._gl.RGB32UI;case Ze.TEXTUREFORMAT_RGBA_INTEGER:default:return this._gl.RGBA32UI}case Ze.TEXTURETYPE_FLOAT:switch(t){case Ze.TEXTUREFORMAT_RED:return this._gl.R32F;case Ze.TEXTUREFORMAT_RG:return this._gl.RG32F;case Ze.TEXTUREFORMAT_RGB:return this._gl.RGB32F;case Ze.TEXTUREFORMAT_RGBA:default:return this._gl.RGBA32F}case Ze.TEXTURETYPE_HALF_FLOAT:switch(t){case Ze.TEXTUREFORMAT_RED:return this._gl.R16F;case Ze.TEXTUREFORMAT_RG:return this._gl.RG16F;case Ze.TEXTUREFORMAT_RGB:return this._gl.RGB16F;case Ze.TEXTUREFORMAT_RGBA:default:return this._gl.RGBA16F}case Ze.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:return this._gl.RGB565;case Ze.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:return this._gl.R11F_G11F_B10F;case Ze.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:return this._gl.RGB9_E5;case Ze.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:return this._gl.RGBA4;case Ze.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:return this._gl.RGB5_A1;case Ze.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:switch(t){case Ze.TEXTUREFORMAT_RGBA:return this._gl.RGB10_A2;case Ze.TEXTUREFORMAT_RGBA_INTEGER:return this._gl.RGB10_A2UI;default:return this._gl.RGB10_A2}}return i?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA8}readPixels(e,t,i,n,r=!0,s=!0){const a=r?4:3,o=r?this._gl.RGBA:this._gl.RGB,l=new Uint8Array(n*i*a);return s&&this.flushFramebuffer(),this._gl.readPixels(e,t,i,n,o,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=vt._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=vt._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}}Ni._TempClearColorUint32=new Uint32Array(4),Ni._TempClearColorInt32=new Int32Array(4),Ni.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"]}],Ni._ConcatenateShader=Ne,Ni._IsSupported=null,Ni._HasMajorPerformanceCaveat=null,Ni.prototype.createUniformBuffer=function(e,t){const i=this._gl.createBuffer();if(!i)throw new Error("Unable to create uniform buffer");const n=new yi(i);return this.bindUniformBuffer(n),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),n.references=1,n},Ni.prototype.createDynamicUniformBuffer=function(e,t){const i=this._gl.createBuffer();if(!i)throw new Error("Unable to create dynamic uniform buffer");const n=new yi(i);return this.bindUniformBuffer(n),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),n.references=1,n},Ni.prototype.updateUniformBuffer=function(e,t,i,n){this.bindUniformBuffer(e),void 0===i&&(i=0),void 0===n?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+n)):this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,0,new Float32Array(t).subarray(i,i+n)),this.bindUniformBuffer(null)},Ni.prototype.bindUniformBuffer=function(e){this._gl.bindBuffer(this._gl.UNIFORM_BUFFER,e?e.underlyingResource:null)},Ni.prototype.bindUniformBufferBase=function(e,t,i){this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER,t,e?e.underlyingResource:null)},Ni.prototype.bindUniformBlock=function(e,t,i){const n=e.program,r=this._gl.getUniformBlockIndex(n,t);4294967295!==r&&this._gl.uniformBlockBinding(n,r,i)};class Pi{constructor(e,t,i,n,r=!1){this._valueCache={},this._engine=e,this._noUBO=!e.supportsUniformBuffers||r,this._dynamic=i,this._name=n??"no-name",this._data=t||[],this._uniformLocations={},this._uniformSizes={},this._uniformArraySizes={},this._uniformLocationPointer=0,this._needSync=!1,this._engine._features.trackUbosInFrame&&(this._buffers=[],this._bufferIndex=-1,this._createBufferOnWrite=!1,this._currentFrameId=0),this._noUBO?(this.updateMatrix3x3=this._updateMatrix3x3ForEffect,this.updateMatrix2x2=this._updateMatrix2x2ForEffect,this.updateFloat=this._updateFloatForEffect,this.updateFloat2=this._updateFloat2ForEffect,this.updateFloat3=this._updateFloat3ForEffect,this.updateFloat4=this._updateFloat4ForEffect,this.updateFloatArray=this._updateFloatArrayForEffect,this.updateArray=this._updateArrayForEffect,this.updateIntArray=this._updateIntArrayForEffect,this.updateUIntArray=this._updateUIntArrayForEffect,this.updateMatrix=this._updateMatrixForEffect,this.updateMatrices=this._updateMatricesForEffect,this.updateVector3=this._updateVector3ForEffect,this.updateVector4=this._updateVector4ForEffect,this.updateColor3=this._updateColor3ForEffect,this.updateColor4=this._updateColor4ForEffect,this.updateDirectColor4=this._updateDirectColor4ForEffect,this.updateInt=this._updateIntForEffect,this.updateInt2=this._updateInt2ForEffect,this.updateInt3=this._updateInt3ForEffect,this.updateInt4=this._updateInt4ForEffect,this.updateUInt=this._updateUIntForEffect,this.updateUInt2=this._updateUInt2ForEffect,this.updateUInt3=this._updateUInt3ForEffect,this.updateUInt4=this._updateUInt4ForEffect):(this._engine._uniformBuffers.push(this),this.updateMatrix3x3=this._updateMatrix3x3ForUniform,this.updateMatrix2x2=this._updateMatrix2x2ForUniform,this.updateFloat=this._updateFloatForUniform,this.updateFloat2=this._updateFloat2ForUniform,this.updateFloat3=this._updateFloat3ForUniform,this.updateFloat4=this._updateFloat4ForUniform,this.updateFloatArray=this._updateFloatArrayForUniform,this.updateArray=this._updateArrayForUniform,this.updateIntArray=this._updateIntArrayForUniform,this.updateUIntArray=this._updateUIntArrayForUniform,this.updateMatrix=this._updateMatrixForUniform,this.updateMatrices=this._updateMatricesForUniform,this.updateVector3=this._updateVector3ForUniform,this.updateVector4=this._updateVector4ForUniform,this.updateColor3=this._updateColor3ForUniform,this.updateColor4=this._updateColor4ForUniform,this.updateDirectColor4=this._updateDirectColor4ForUniform,this.updateInt=this._updateIntForUniform,this.updateInt2=this._updateInt2ForUniform,this.updateInt3=this._updateInt3ForUniform,this.updateInt4=this._updateInt4ForUniform,this.updateUInt=this._updateUIntForUniform,this.updateUInt2=this._updateUInt2ForUniform,this.updateUInt3=this._updateUInt3ForUniform,this.updateUInt4=this._updateUInt4ForUniform)}get useUbo(){return!this._noUBO}get isSync(){return!this._needSync}isDynamic(){return 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;e<i;e++)this._data.push(0)}}addUniform(e,t,i=0){if(this._noUBO)return;if(void 0!==this._uniformLocations[e])return;let n;if(i>0){if(t instanceof Array)throw"addUniform should not be use with Array in UBO: "+e;if(this._fillAlignment(4),this._uniformArraySizes[e]={strideSize:t,arraySize:i},16==t)t*=i;else{t=t*i+(4-t)*i}n=[];for(let e=0;e<t;e++)n.push(0)}else{if(t instanceof Array)n=t,t=n.length;else{n=[];for(let e=0;e<t;e++)n.push(0)}this._fillAlignment(t)}this._uniformSizes[e]=t,this._uniformLocations[e]=this._uniformLocationPointer,this._uniformLocationPointer+=t;for(let e=0;e<t;e++)this._data.push(n[e]);this._needSync=!0}addMatrix(e,t){this.addUniform(e,Array.prototype.slice.call(t.asArray()))}addFloat2(e,t,i){const n=[t,i];this.addUniform(e,n)}addFloat3(e,t,i,n){const r=[t,i,n];this.addUniform(e,r)}addColor3(e,t){const i=[t.r,t.g,t.b];this.addUniform(e,i)}addColor4(e,t,i){const n=[t.r,t.g,t.b,i];this.addUniform(e,n)}addVector3(e,t){const i=[t.x,t.y,t.z];this.addUniform(e,i)}addMatrix3x3(e){this.addUniform(e,12)}addMatrix2x2(e){this.addUniform(e,8)}create(){this._noUBO||this._buffer||(this._fillAlignment(4),this._bufferData=new Float32Array(this._data),this._rebuild(),this._needSync=!0)}_getNames(){const e=[];let t=0;for(const i in this._uniformLocations)if(e.push(i),10==++t)break;return e.join(",")}_rebuild(){!this._noUBO&&this._bufferData&&(this._dynamic?this._buffer=this._engine.createDynamicUniformBuffer(this._bufferData,this._name+"_UniformList:"+this._getNames()):this._buffer=this._engine.createUniformBuffer(this._bufferData,this._name+"_UniformList:"+this._getNames()),this._engine._features.trackUbosInFrame&&(this._buffers.push([this._buffer,this._engine._features.checkUbosContentBeforeUpload?this._bufferData.slice():void 0]),this._bufferIndex=this._buffers.length-1,this._createBufferOnWrite=!1))}_rebuildAfterContextLost(){this._engine._features.trackUbosInFrame&&(this._buffers=[],this._currentFrameId=0),this._rebuild()}get _numBuffers(){return this._buffers.length}get _indexBuffer(){return this._bufferIndex}get name(){return this._name}get currentEffect(){return this._currentEffect}_buffersEqual(e,t){for(let i=0;i<e.length;++i)if(e[i]!==t[i])return!1;return!0}_copyBuffer(e,t){for(let i=0;i<e.length;++i)t[i]=e[i]}update(){if(!this._noUBO)if(this.bindUniformBuffer(),this._buffer)if(this._dynamic||this._needSync){if(this._buffers&&this._buffers.length>1&&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&&(Pi._UpdatedUbosInFrame[this._name]||(Pi._UpdatedUbosInFrame[this._name]=0),Pi._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+1<this._buffers.length?(this._bufferIndex++,this._buffer=this._buffers[this._bufferIndex][0],this._createBufferOnWrite=!1,this._needSync=!0):this._rebuild()}_checkNewFrame(){this._engine._features.trackUbosInFrame&&this._currentFrameId!==this._engine.frameId&&(this._currentFrameId=this._engine.frameId,this._createBufferOnWrite=!1,this._buffers&&this._buffers.length>0?(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 n=this._uniformLocations[e];if(void 0===n){if(this._buffer)return void de.Error("Cannot add an uniform after UBO has been created. uniformName="+e);this.addUniform(e,i),n=this._uniformLocations[e]}if(this._buffer||this.create(),this._dynamic)for(let e=0;e<i;e++)this._bufferData[n+e]=t[e];else{let e=!1;for(let r=0;r<i;r++)(16===i&&!this._engine._features.uniformBufferHardCheckMatrix||this._bufferData[n+r]!==Math.fround(t[r]))&&(e=!0,this._createBufferOnWrite&&this._createNewBuffer(),this._bufferData[n+r]=t[r]);this._needSync=this._needSync||e}}updateUniformArray(e,t,i){this._checkNewFrame();const n=this._uniformLocations[e];if(void 0===n)return void de.Error("Cannot add an uniform Array dynamically. Please, add it using addUniform and make sure that uniform buffers are supported by the current engine.");this._buffer||this.create();const r=this._uniformArraySizes[e];if(this._dynamic)for(let e=0;e<i;e++)this._bufferData[n+e]=t[e];else{let e=!1,s=0,a=0;for(let o=0;o<i;o++)if(this._bufferData[n+4*a+s]!==Yt.FloatRound(t[o])&&(e=!0,this._createBufferOnWrite&&this._createNewBuffer(),this._bufferData[n+4*a+s]=t[o]),s++,s===r.strideSize){for(;s<4;s++)this._bufferData[n+4*a+s]=0;s=0,a++}this._needSync=this._needSync||e}}_cacheMatrix(e,t){this._checkNewFrame();const i=this._valueCache[e],n=t.updateFlag;return(void 0===i||i!==n)&&(this._valueCache[e]=n,!0)}_updateMatrix3x3ForUniform(e,t){for(let e=0;e<3;e++)Pi._TempBuffer[4*e]=t[3*e],Pi._TempBuffer[4*e+1]=t[3*e+1],Pi._TempBuffer[4*e+2]=t[3*e+2],Pi._TempBuffer[4*e+3]=0;this.updateUniform(e,Pi._TempBuffer,12)}_updateMatrix3x3ForEffect(e,t){this._currentEffect.setMatrix3x3(e,t)}_updateMatrix2x2ForEffect(e,t){this._currentEffect.setMatrix2x2(e,t)}_updateMatrix2x2ForUniform(e,t){for(let e=0;e<2;e++)Pi._TempBuffer[4*e]=t[2*e],Pi._TempBuffer[4*e+1]=t[2*e+1],Pi._TempBuffer[4*e+2]=0,Pi._TempBuffer[4*e+3]=0;this.updateUniform(e,Pi._TempBuffer,8)}_updateFloatForEffect(e,t){this._currentEffect.setFloat(e,t)}_updateFloatForUniform(e,t){Pi._TempBuffer[0]=t,this.updateUniform(e,Pi._TempBuffer,1)}_updateFloat2ForEffect(e,t,i,n=""){this._currentEffect.setFloat2(e+n,t,i)}_updateFloat2ForUniform(e,t,i){Pi._TempBuffer[0]=t,Pi._TempBuffer[1]=i,this.updateUniform(e,Pi._TempBuffer,2)}_updateFloat3ForEffect(e,t,i,n,r=""){this._currentEffect.setFloat3(e+r,t,i,n)}_updateFloat3ForUniform(e,t,i,n){Pi._TempBuffer[0]=t,Pi._TempBuffer[1]=i,Pi._TempBuffer[2]=n,this.updateUniform(e,Pi._TempBuffer,3)}_updateFloat4ForEffect(e,t,i,n,r,s=""){this._currentEffect.setFloat4(e+s,t,i,n,r)}_updateFloat4ForUniform(e,t,i,n,r){Pi._TempBuffer[0]=t,Pi._TempBuffer[1]=i,Pi._TempBuffer[2]=n,Pi._TempBuffer[3]=r,this.updateUniform(e,Pi._TempBuffer,4)}_updateFloatArrayForEffect(e,t){this._currentEffect.setFloatArray(e,t)}_updateFloatArrayForUniform(e,t){this.updateUniformArray(e,t,t.length)}_updateArrayForEffect(e,t){this._currentEffect.setArray(e,t)}_updateArrayForUniform(e,t){this.updateUniformArray(e,t,t.length)}_updateIntArrayForEffect(e,t){this._currentEffect.setIntArray(e,t)}_updateIntArrayForUniform(e,t){Pi._TempBufferInt32View.set(t),this.updateUniformArray(e,Pi._TempBuffer,t.length)}_updateUIntArrayForEffect(e,t){this._currentEffect.setUIntArray(e,t)}_updateUIntArrayForUniform(e,t){Pi._TempBufferUInt32View.set(t),this.updateUniformArray(e,Pi._TempBuffer,t.length)}_updateMatrixForEffect(e,t){this._currentEffect.setMatrix(e,t)}_updateMatrixForUniform(e,t){this._cacheMatrix(e,t)&&this.updateUniform(e,t.asArray(),16)}_updateMatricesForEffect(e,t){this._currentEffect.setMatrices(e,t)}_updateMatricesForUniform(e,t){this.updateUniform(e,t,t.length)}_updateVector3ForEffect(e,t){this._currentEffect.setVector3(e,t)}_updateVector3ForUniform(e,t){Pi._TempBuffer[0]=t.x,Pi._TempBuffer[1]=t.y,Pi._TempBuffer[2]=t.z,this.updateUniform(e,Pi._TempBuffer,3)}_updateVector4ForEffect(e,t){this._currentEffect.setVector4(e,t)}_updateVector4ForUniform(e,t){Pi._TempBuffer[0]=t.x,Pi._TempBuffer[1]=t.y,Pi._TempBuffer[2]=t.z,Pi._TempBuffer[3]=t.w,this.updateUniform(e,Pi._TempBuffer,4)}_updateColor3ForEffect(e,t,i=""){this._currentEffect.setColor3(e+i,t)}_updateColor3ForUniform(e,t){Pi._TempBuffer[0]=t.r,Pi._TempBuffer[1]=t.g,Pi._TempBuffer[2]=t.b,this.updateUniform(e,Pi._TempBuffer,3)}_updateColor4ForEffect(e,t,i,n=""){this._currentEffect.setColor4(e+n,t,i)}_updateDirectColor4ForEffect(e,t,i=""){this._currentEffect.setDirectColor4(e+i,t)}_updateColor4ForUniform(e,t,i){Pi._TempBuffer[0]=t.r,Pi._TempBuffer[1]=t.g,Pi._TempBuffer[2]=t.b,Pi._TempBuffer[3]=i,this.updateUniform(e,Pi._TempBuffer,4)}_updateDirectColor4ForUniform(e,t){Pi._TempBuffer[0]=t.r,Pi._TempBuffer[1]=t.g,Pi._TempBuffer[2]=t.b,Pi._TempBuffer[3]=t.a,this.updateUniform(e,Pi._TempBuffer,4)}_updateIntForEffect(e,t,i=""){this._currentEffect.setInt(e+i,t)}_updateIntForUniform(e,t){Pi._TempBufferInt32View[0]=t,this.updateUniform(e,Pi._TempBuffer,1)}_updateInt2ForEffect(e,t,i,n=""){this._currentEffect.setInt2(e+n,t,i)}_updateInt2ForUniform(e,t,i){Pi._TempBufferInt32View[0]=t,Pi._TempBufferInt32View[1]=i,this.updateUniform(e,Pi._TempBuffer,2)}_updateInt3ForEffect(e,t,i,n,r=""){this._currentEffect.setInt3(e+r,t,i,n)}_updateInt3ForUniform(e,t,i,n){Pi._TempBufferInt32View[0]=t,Pi._TempBufferInt32View[1]=i,Pi._TempBufferInt32View[2]=n,this.updateUniform(e,Pi._TempBuffer,3)}_updateInt4ForEffect(e,t,i,n,r,s=""){this._currentEffect.setInt4(e+s,t,i,n,r)}_updateInt4ForUniform(e,t,i,n,r){Pi._TempBufferInt32View[0]=t,Pi._TempBufferInt32View[1]=i,Pi._TempBufferInt32View[2]=n,Pi._TempBufferInt32View[3]=r,this.updateUniform(e,Pi._TempBuffer,4)}_updateUIntForEffect(e,t,i=""){this._currentEffect.setUInt(e+i,t)}_updateUIntForUniform(e,t){Pi._TempBufferUInt32View[0]=t,this.updateUniform(e,Pi._TempBuffer,1)}_updateUInt2ForEffect(e,t,i,n=""){this._currentEffect.setUInt2(e+n,t,i)}_updateUInt2ForUniform(e,t,i){Pi._TempBufferUInt32View[0]=t,Pi._TempBufferUInt32View[1]=i,this.updateUniform(e,Pi._TempBuffer,2)}_updateUInt3ForEffect(e,t,i,n,r=""){this._currentEffect.setUInt3(e+r,t,i,n)}_updateUInt3ForUniform(e,t,i,n){Pi._TempBufferUInt32View[0]=t,Pi._TempBufferUInt32View[1]=i,Pi._TempBufferUInt32View[2]=n,this.updateUniform(e,Pi._TempBuffer,3)}_updateUInt4ForEffect(e,t,i,n,r,s=""){this._currentEffect.setUInt4(e+s,t,i,n,r)}_updateUInt4ForUniform(e,t,i,n,r){Pi._TempBufferUInt32View[0]=t,Pi._TempBufferUInt32View[1]=i,Pi._TempBufferUInt32View[2]=n,Pi._TempBufferUInt32View[3]=r,this.updateUniform(e,Pi._TempBuffer,4)}setTexture(e,t){this._currentEffect.setTexture(e,t)}bindTexture(e,t){this._currentEffect._bindTexture(e,t)}updateUniformDirectly(e,t){this.updateUniform(e,t,t.length),this.update()}bindToEffect(e,t){this._currentEffect=e,this._currentEffectName=t}bindUniformBuffer(){!this._noUBO&&this._buffer&&this._currentEffect&&this._currentEffect.bindUniformBuffer(this._buffer,this._currentEffectName)}unbindEffect(){this._currentEffect=void 0,this._currentEffectName=void 0}setDataBuffer(e){if(!this._buffers)return this._buffer===e;for(let t=0;t<this._buffers.length;++t){if(this._buffers[t][0]===e)return this._bufferIndex=t,this._buffer=e,this._createBufferOnWrite=!1,this._currentEffect=void 0,!0}return!1}dispose(){if(this._noUBO)return;const e=this._engine._uniformBuffers,t=e.indexOf(this);if(-1!==t&&(e[t]=e[e.length-1],e.pop()),this._engine._features.trackUbosInFrame&&this._buffers)for(let e=0;e<this._buffers.length;++e){const t=this._buffers[e][0];this._engine._releaseBuffer(t)}else this._buffer&&this._engine._releaseBuffer(this._buffer)&&(this._buffer=null)}}Pi._UpdatedUbosInFrame={},Pi._MAX_UNIFORM_SIZE=256,Pi._TempBuffer=new Float32Array(Pi._MAX_UNIFORM_SIZE),Pi._TempBufferInt32View=new Int32Array(Pi._TempBuffer.buffer),Pi._TempBufferUInt32View=new Uint32Array(Pi._TempBuffer.buffer);class Li{constructor(){this._checkCollisions=!1,this._collisionMask=-1,this._collisionGroup=-1,this._surroundingMeshes=null,this._collider=null,this._oldPositionForCollisions=new B(0,0,0),this._diffPositionForCollisions=new B(0,0,0),this._collisionResponse=!0}}var Fi,wi;!function(e){e[e.LOCAL=0]="LOCAL",e[e.WORLD=1]="WORLD",e[e.BONE=2]="BONE"}(Fi||(Fi={}));class Ui{}Ui.X=new B(1,0,0),Ui.Y=new B(0,1,0),Ui.Z=new B(0,0,1),function(e){e[e.X=0]="X",e[e.Y=1]="Y",e[e.Z=2]="Z"}(wi||(wi={}));class Bi{constructor(){this.facetNb=0,this.partitioningSubdivisions=10,this.partitioningBBoxRatio=1.01,this.facetDataEnabled=!1,this.facetParameters={},this.bbSize=B.Zero(),this.subDiv={max:1,X:1,Y:1,Z:1},this.facetDepthSort=!1,this.facetDepthSortEnabled=!1}}class Gi{constructor(){this._hasVertexAlpha=!1,this._useVertexColors=!0,this._numBoneInfluencers=4,this._applyFog=!0,this._receiveShadows=!1,this._facetData=new Bi,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 Li,this._enableDistantPicking=!1,this._rawBoundingInfo=null,this._sideOrientationHint=!1,this._inheritVisibility=!1}}class Vi extends Si{static get BILLBOARDMODE_NONE(){return Si.BILLBOARDMODE_NONE}static get BILLBOARDMODE_X(){return Si.BILLBOARDMODE_X}static get BILLBOARDMODE_Y(){return Si.BILLBOARDMODE_Y}static get BILLBOARDMODE_Z(){return Si.BILLBOARDMODE_Z}static get BILLBOARDMODE_ALL(){return Si.BILLBOARDMODE_ALL}static get BILLBOARDMODE_USE_POSITION(){return Si.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 Gi,this._waitingMaterialId=null,this.cullingStrategy=Vi.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY,this.onCollideObservable=new g,this.onCollisionPositionChangeObservable=new g,this.onMaterialChangedObservable=new g,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=ee.Red(),this.outlineWidth=.02,this.overlayColor=ee.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 B(.5,1,.5),this.ellipsoidOffset=new B(0,0,0),this.edgesWidth=1,this.edgesColor=new te(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 g,this._onCollisionPositionChange=(e,t,i=null)=>{t.subtractToRef(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions.length()>vt.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 Pi(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!==Si.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 n=!1;if(-1===i){if(!t)return;this._lightSources.push(e)}else{if(t)return;n=!0,this._lightSources.splice(i,1)}this._markSubMeshesAsLightDirty(n)}_unBindEffect(){for(const e of this.subMeshes)e.setEffect(null)}_removeLightSource(e,t){const i=this._lightSources.indexOf(e);-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;i<t._drawWrappers.length;++i){const n=t._drawWrappers[i];n&&n.defines&&n.defines.markAllAsDirty&&e(n.defines)}}_markSubMeshesAsLightDirty(e=!1){this._markSubMeshesAsDirty((t=>t.markAsLightDirty(e)))}_markSubMeshesAsAttributesDirty(){this._markSubMeshesAsDirty((e=>e.markAsAttributesDirty()))}_markSubMeshesAsMiscDirty(){this._markSubMeshesAsDirty((e=>e.markAsMiscDirty()))}markAsDirty(e){return this._currentRenderId=Number.MAX_VALUE,this._isDirty=!0,this}resetDrawCache(e){if(this.subMeshes)for(const t of this.subMeshes)t.resetDrawCache(e)}get isBlocked(){return!1}getLOD(e){return this}getTotalVertices(){return 0}getTotalIndices(){return 0}getIndices(){return null}getVerticesData(e){return null}setVerticesData(e,t,i,n){return this}updateVerticesData(e,t,i,n){return this}setIndices(e,t){return this}isVerticesDataPresent(e){return!1}getBoundingInfo(){return this._masterMesh?this._masterMesh.getBoundingInfo():(this._boundingInfoIsDirty&&(this._boundingInfoIsDirty=!1,this._updateBoundingInfo()),this._boundingInfo)}getRawBoundingInfo(){return this.rawBoundingInfo??this.getBoundingInfo()}setBoundingInfo(e){return this._boundingInfo=e,this}get hasBoundingInfo(){return null!==this._boundingInfo}buildBoundingInfo(e,t,i){return this._boundingInfo=new fi(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(si.MatricesIndicesKind)&&this.isVerticesDataPresent(si.MatricesWeightsKind)}_preActivate(){}_preActivateForIntermediateRendering(e){}_activate(e,t){return this._renderId=e,!0}_postActivate(){}_freeze(){}_unFreeze(){}getWorldMatrix(){return this._masterMesh&&this.billboardMode===Si.BILLBOARDMODE_NONE?this._masterMesh.getWorldMatrix():super.getWorldMatrix()}_getWorldMatrixDeterminant(){return this._masterMesh?this._masterMesh._getWorldMatrixDeterminant():super._getWorldMatrixDeterminant()}get isAnInstance(){return!1}get hasInstances(){return!1}get hasThinInstances(){return!1}movePOV(e,t,i){return this.position.addInPlace(this.calcMovePOV(e,t,i)),this}calcMovePOV(e,t,i){const n=new k;(this.rotationQuaternion?this.rotationQuaternion:V.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z)).toRotationMatrix(n);const r=B.Zero(),s=this.definedFacingForward?-1:1;return B.TransformCoordinatesFromFloatsToRef(e*s,t,i*s,n,r),r}rotatePOV(e,t,i){return this.rotation.addInPlace(this.calcRotatePOV(e,t,i)),this}calcRotatePOV(e,t,i){const n=this.definedFacingForward?1:-1;return new B(e*n,t,i*n)}_refreshBoundingInfo(e,t){if(e){const i=mi(e,0,this.getTotalVertices(),t);this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new fi(i.minimum,i.maximum)}if(this.subMeshes)for(let t=0;t<this.subMeshes.length;t++)this.subMeshes[t].refreshBoundingInfo(e);this._updateBoundingInfo()}_refreshBoundingInfoDirect(e){if(this._boundingInfo?this._boundingInfo.reConstruct(e.minimum,e.maximum):this._boundingInfo=new fi(e.minimum,e.maximum),this.subMeshes)for(let e=0;e<this.subMeshes.length;e++)this.subMeshes[e].refreshBoundingInfo(null);this._updateBoundingInfo()}static _ApplySkeleton(e,t,i,n,r,s,a){!function(e,t,i,n,r,s,a){const o=H.Vector3[0],l=H.Matrix[0],c=H.Matrix[1],h=t===si.NormalKind?B.TransformNormalFromFloatsToRef:B.TransformCoordinatesFromFloatsToRef;for(let t=0,d=0;t<e.length;t+=3,d+=4){let u,f;for(l.reset(),u=0;u<4;u++)f=r[d+u],f>0&&(k.FromFloat32ArrayToRefScaled(i,Math.floor(16*n[d+u]),f,c),l.addToSelf(c));if(s&&a)for(u=0;u<4;u++)f=a[d+u],f>0&&(k.FromFloat32ArrayToRefScaled(i,Math.floor(16*s[d+u]),f,c),l.addToSelf(c));h(e[t],e[t+1],e[t+2],l,o),o.toArray(e,t)}}(e,t,i,n,r,s,a)}_getData(e,t,i=si.PositionKind){const n=e.cache,r=e=>{if(n){const t=n._vertexData||={};return t[e]||this.copyVerticesData(e,t),t[e]}return this.getVerticesData(e)};if(t||=r(i),!t)return null;if(n?(n._outputData?n._outputData.set(t):n._outputData=new Float32Array(t),t=n._outputData):(e.applyMorph&&this.morphTargetManager||e.applySkeleton&&this.skeleton)&&(t=t.slice()),e.applyMorph&&this.morphTargetManager&&function(e,t,i){let n=null;switch(t){case si.PositionKind:n=e=>e.getPositions();break;case si.NormalKind:n=e=>e.getNormals();break;case si.TangentKind:n=e=>e.getTangents();break;case si.UVKind:n=e=>e.getUVs();break;default:return}for(let t=0;t<e.length;t++){let r=e[t];for(let s=0;s<i.numTargets;s++){const a=i.getTarget(s),o=a.influence;if(0!==o){const i=n(a);i&&(r+=(i[t]-e[t])*o)}}e[t]=r}}(t,i,this.morphTargetManager),e.applySkeleton&&this.skeleton){const e=r(si.MatricesIndicesKind),n=r(si.MatricesWeightsKind);if(n&&e){const s=this.numBoneInfluencers>4,a=s?r(si.MatricesIndicesExtraKind):null,o=s?r(si.MatricesWeightsExtraKind):null,l=this.skeleton.getTransformMatrices(this);Vi._ApplySkeleton(t,i,l,e,n,a,o)}}if(!1!==e.updatePositionsArray&&i===si.PositionKind){const e=this._internalAbstractMeshDataInfo._positions||[],i=e.length;if(e.length=t.length/3,i<e.length)for(let t=i;t<e.length;t++)e[t]=new B;for(let i=0,n=0;i<e.length;i++,n+=3)e[i].copyFromFloats(t[n],t[n+1],t[n+2]);this._internalAbstractMeshDataInfo._positions=e}return t}getNormalsData(e=!1,t=!1){return this._getData({applySkeleton:e,applyMorph:t,updatePositionsArray:!1},null,si.NormalKind)}getPositionData(e=!1,t=!1,i=null){return this._getData({applySkeleton:e,applyMorph:t,updatePositionsArray:!1},i,si.PositionKind)}_updateBoundingInfo(){return this._boundingInfo?this._boundingInfo.update(this.worldMatrixFromCache):this._boundingInfo=new fi(B.Zero(),B.Zero(),this.worldMatrixFromCache),this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache),this}_updateSubMeshesBoundingInfo(e){if(!this.subMeshes)return this;const t=this.subMeshes.length;for(let i=0;i<t;i++){const n=this.subMeshes[i];(t>1||!n.IsGlobal)&&n.updateBoundingInfo(e)}return this}_afterComputeWorldMatrix(){this.doNotSyncBoundingInfo||(this._boundingInfoIsDirty=!0)}isInFrustum(e){return this.getBoundingInfo().isInFrustum(e,this.cullingStrategy)}isCompletelyInFrustum(e){return this.getBoundingInfo().isCompletelyInFrustum(e)}intersectsMesh(e,t=!1,i){const n=this.getBoundingInfo(),r=e.getBoundingInfo();if(n.intersects(r,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,n=e.verticesStart+e.verticesCount;for(let r=i;r<n;r++)e._lastColliderWorldVertices.push(B.TransformCoordinates(this._positions[r],t))}return i._collide(e._trianglePlanes,e._lastColliderWorldVertices,this.getIndices(),e.indexStart,e.indexStart+e.indexCount,e.verticesStart,!!e.getMaterial(),this,this._shouldConvertRHS(),e.getMaterial()?.fillMode===Ze.MATERIAL_TriangleStripDrawMode),this}_processCollisionsForSubMeshes(e,t){const i=this._scene.getCollidingSubMeshCandidates(this,e),n=i.length;for(let r=0;r<n;r++){const s=i.data[r];n>1&&!s._checkCollision(e)||this._collideForSubMesh(s,t,e)}return this}_shouldConvertRHS(){return!1}_checkCollision(e){if(!this.getBoundingInfo()._checkCollision(e))return this;const t=H.Matrix[0],i=H.Matrix[1];return k.ScalingToRef(1/e._radius.x,1/e._radius.y,1/e._radius.z,t),this.worldMatrixFromCache.multiplyToRef(t,i),this._processCollisionsForSubMeshes(e,i),this}_generatePointsArray(){return!1}intersects(e,t,i,n=!1,r,s=!1){const a=new Ci,o=this.getClassName(),l="InstancedLinesMesh"===o||"LinesMesh"===o||"GreasedLineMesh"===o?this.intersectionThreshold:0,c=this.getBoundingInfo();if(!this.subMeshes)return a;if(!(s||e.intersectsSphere(c.boundingSphere,l)&&e.intersectsBox(c.boundingBox,l)))return a;if(n)return a.hit=!s,a.pickedMesh=s?null:this,a.distance=s?0:B.Distance(e.origin,c.boundingSphere.center),a.subMeshId=0,a;if(!this._generatePointsArray())return a;let h=null;const d=this._scene.getIntersectingSubMeshCandidates(this,e),u=d.length;let f=!1;for(let e=0;e<u;e++){const t=d.data[e].getMaterial();if(t&&(t.fillMode==Ze.MATERIAL_TriangleStripDrawMode||t.fillMode==Ze.MATERIAL_TriangleFillMode||t.fillMode==Ze.MATERIAL_WireFrameFillMode||t.fillMode==Ze.MATERIAL_PointFillMode||t.fillMode==Ze.MATERIAL_LineListDrawMode)){f=!0;break}}if(!f)return a.hit=!0,a.pickedMesh=this,a.distance=B.Distance(e.origin,c.boundingSphere.center),a.subMeshId=-1,a;for(let n=0;n<u;n++){const r=d.data[n];if(u>1&&!s&&!r.canIntersects(e))continue;const a=r.intersects(e,this._positions,this.getIndices(),t,i);if(a&&(t||!h||a.distance<h.distance)&&(h=a,h.subMeshId=n,t))break}if(h){const t=r??this.getWorldMatrix(),i=H.Vector3[0],n=H.Vector3[1];B.TransformCoordinatesToRef(e.origin,t,i),e.direction.scaleToRef(h.distance,n);const s=B.TransformNormal(n,t).addInPlace(i);return a.hit=!0,a.distance=B.Distance(i,s),a.pickedPoint=s,a.pickedMesh=this,a.bu=h.bu||0,a.bv=h.bv||0,a.subMeshFaceId=h.faceId,a.faceId=h.faceId+d.data[h.subMeshId].indexStart/(-1!==this.getClassName().indexOf("LinesMesh")?2:3),a.subMeshId=h.subMeshId,a}return a}clone(e,t,i){return null}releaseSubMeshes(){if(this.subMeshes)for(;this.subMeshes.length;)this.subMeshes[0].dispose();else this.subMeshes=[];return this}dispose(e,t=!1){let i;const n=this.getScene();for(this._scene.useMaterialMeshMap&&this._internalAbstractMeshDataInfo._material&&this._internalAbstractMeshDataInfo._material.meshMap&&(this._internalAbstractMeshDataInfo._material.meshMap[this.uniqueId]=void 0),n.freeActiveMeshes(),n.freeRenderingGroups(),n.renderingManager.maintainStateBetweenFrames&&n.renderingManager.restoreDispachedFlags(),void 0!==this.actionManager&&null!==this.actionManager&&(this.actionManager.disposeWhenUnowned&&!this._scene.meshes.some((e=>e!==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<this._intersectionsInProgress.length;i++){const e=this._intersectionsInProgress[i],t=e._intersectionsInProgress.indexOf(this);e._intersectionsInProgress.splice(t,1)}this._intersectionsInProgress.length=0;n.lights.forEach((e=>{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 r=n.getEngine();if(null!==this._occlusionQuery&&(this.isOcclusionQueryInProgress=!1,r.deleteQuery(this._occlusionQuery),this._occlusionQuery=null),r.wipeCaches(),n.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;i<n.particleSystems.length;i++)n.particleSystems[i].emitter===this&&(n.particleSystems[i].dispose(),i--);this._internalAbstractMeshDataInfo._facetData.facetDataEnabled&&this.disableFacetData(),this._uniformBuffer.dispose(),this.onAfterWorldMatrixUpdateObservable.clear(),this.onCollideObservable.clear(),this.onCollisionPositionChangeObservable.clear(),this.onRebuildObservable.clear(),super.dispose(e,t)}_initFacetData(){const e=this._internalAbstractMeshDataInfo._facetData;e.facetNormals||(e.facetNormals=[]),e.facetPositions||(e.facetPositions=[]),e.facetPartitioning||(e.facetPartitioning=new Array),e.facetNb=this.getIndices().length/3|0,e.partitioningSubdivisions=e.partitioningSubdivisions?e.partitioningSubdivisions:10,e.partitioningBBoxRatio=e.partitioningBBoxRatio?e.partitioningBBoxRatio:1.01;for(let t=0;t<e.facetNb;t++)e.facetNormals[t]=B.Zero(),e.facetPositions[t]=B.Zero();return e.facetDataEnabled=!0,this}updateFacetData(){const e=this._internalAbstractMeshDataInfo._facetData;e.facetDataEnabled||this._initFacetData();const t=this.getVerticesData(si.PositionKind),i=this.getIndices(),n=this.getVerticesData(si.NormalKind),r=this.getBoundingInfo();if(e.facetDepthSort&&!e.facetDepthSortEnabled){if(e.facetDepthSortEnabled=!0,i instanceof Uint16Array)e.depthSortedIndices=new Uint16Array(i);else if(i instanceof Uint32Array)e.depthSortedIndices=new Uint32Array(i);else{let t=!1;for(let e=0;e<i.length;e++)if(i[e]>65535){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:B.Zero()}e.depthSortedFacets=[];for(let t=0;t<e.facetNb;t++){const i={ind:3*t,sqDistance:0};e.depthSortedFacets.push(i)}e.invertedMatrix=k.Identity(),e.facetDepthSortOrigin=B.Zero()}e.bbSize.x=r.maximum.x-r.minimum.x>A?r.maximum.x-r.minimum.x:A,e.bbSize.y=r.maximum.y-r.minimum.y>A?r.maximum.y-r.minimum.y:A,e.bbSize.z=r.maximum.z-r.minimum.z>A?r.maximum.z-r.minimum.z:A;let s=e.bbSize.x>e.bbSize.y?e.bbSize.x:e.bbSize.y;if(s=s>e.bbSize.z?s:e.bbSize.z,e.subDiv.max=e.partitioningSubdivisions,e.subDiv.X=Math.floor(e.subDiv.max*e.bbSize.x/s),e.subDiv.Y=Math.floor(e.subDiv.max*e.bbSize.y/s),e.subDiv.Z=Math.floor(e.subDiv.max*e.bbSize.z/s),e.subDiv.X=e.subDiv.X<1?1:e.subDiv.X,e.subDiv.Y=e.subDiv.Y<1?1:e.subDiv.Y,e.subDiv.Z=e.subDiv.Z<1?1:e.subDiv.Z,e.facetParameters.facetNormals=this.getFacetLocalNormals(),e.facetParameters.facetPositions=this.getFacetLocalPositions(),e.facetParameters.facetPartitioning=this.getFacetLocalPartitioning(),e.facetParameters.bInfo=r,e.facetParameters.bbSize=e.bbSize,e.facetParameters.subDiv=e.subDiv,e.facetParameters.ratio=this.partitioningBBoxRatio,e.facetParameters.depthSort=e.facetDepthSort,e.facetDepthSort&&e.facetDepthSortEnabled&&(this.computeWorldMatrix(!0),this._worldMatrix.invertToRef(e.invertedMatrix),B.TransformCoordinatesToRef(e.facetDepthSortFrom,e.invertedMatrix,e.facetDepthSortOrigin),e.facetParameters.distanceTo=e.facetDepthSortOrigin),e.facetParameters.depthSortedFacets=e.depthSortedFacets,n&&Ti.ComputeNormals(t,i,n,e.facetParameters),e.facetDepthSort&&e.facetDepthSortEnabled){e.depthSortedFacets.sort(e.facetDepthSortFunction);const t=e.depthSortedIndices.length/3|0;for(let n=0;n<t;n++){const t=e.depthSortedFacets[n].ind;e.depthSortedIndices[3*n]=i[t],e.depthSortedIndices[3*n+1]=i[t+1],e.depthSortedIndices[3*n+2]=i[t+2]}this.updateIndices(e.depthSortedIndices,void 0,!0)}return this}getFacetLocalNormals(){const e=this._internalAbstractMeshDataInfo._facetData;return e.facetNormals||this.updateFacetData(),e.facetNormals}getFacetLocalPositions(){const e=this._internalAbstractMeshDataInfo._facetData;return e.facetPositions||this.updateFacetData(),e.facetPositions}getFacetLocalPartitioning(){const e=this._internalAbstractMeshDataInfo._facetData;return e.facetPartitioning||this.updateFacetData(),e.facetPartitioning}getFacetPosition(e){const t=B.Zero();return this.getFacetPositionToRef(e,t),t}getFacetPositionToRef(e,t){const i=this.getFacetLocalPositions()[e],n=this.getWorldMatrix();return B.TransformCoordinatesToRef(i,n,t),this}getFacetNormal(e){const t=B.Zero();return this.getFacetNormalToRef(e,t),t}getFacetNormalToRef(e,t){const i=this.getFacetLocalNormals()[e];return B.TransformNormalToRef(i,this.getWorldMatrix(),t),this}getFacetsAtLocalCoordinates(e,t,i){const n=this.getBoundingInfo(),r=this._internalAbstractMeshDataInfo._facetData,s=Math.floor((e-n.minimum.x*r.partitioningBBoxRatio)*r.subDiv.X*r.partitioningBBoxRatio/r.bbSize.x),a=Math.floor((t-n.minimum.y*r.partitioningBBoxRatio)*r.subDiv.Y*r.partitioningBBoxRatio/r.bbSize.y),o=Math.floor((i-n.minimum.z*r.partitioningBBoxRatio)*r.subDiv.Z*r.partitioningBBoxRatio/r.bbSize.z);return s<0||s>r.subDiv.max||a<0||a>r.subDiv.max||o<0||o>r.subDiv.max?null:r.facetPartitioning[s+r.subDiv.max*a+r.subDiv.max*r.subDiv.max*o]}getClosestFacetAtCoordinates(e,t,i,n,r=!1,s=!0){const a=this.getWorldMatrix(),o=H.Matrix[5];a.invertToRef(o);const l=H.Vector3[8];B.TransformCoordinatesFromFloatsToRef(e,t,i,o,l);const c=this.getClosestFacetAtLocalCoordinates(l.x,l.y,l.z,n,r,s);return n&&B.TransformCoordinatesFromFloatsToRef(n.x,n.y,n.z,a,n),c}getClosestFacetAtLocalCoordinates(e,t,i,n,r=!1,s=!0){let a=null,o=0,l=0,c=0,h=0,d=0,u=0,f=0,_=0;const m=this.getFacetLocalPositions(),p=this.getFacetLocalNormals(),g=this.getFacetsAtLocalCoordinates(e,t,i);if(!g)return null;let E,T,A,v=Number.MAX_VALUE,R=v;for(let S=0;S<g.length;S++)E=g[S],T=p[E],A=m[E],h=(e-A.x)*T.x+(t-A.y)*T.y+(i-A.z)*T.z,(!r||r&&s&&h>=0||r&&!s&&h<=0)&&(h=T.x*A.x+T.y*A.y+T.z*A.z,d=-(T.x*e+T.y*t+T.z*i-h)/(T.x*T.x+T.y*T.y+T.z*T.z),u=e+T.x*d,f=t+T.y*d,_=i+T.z*d,o=u-e,l=f-t,c=_-i,R=o*o+l*l+c*c,R<v&&(v=R,a=E,n&&(n.x=u,n.y=f,n.z=_)));return a}getFacetDataParameters(){return this._internalAbstractMeshDataInfo._facetData.facetParameters}disableFacetData(){const e=this._internalAbstractMeshDataInfo._facetData;return e.facetDataEnabled&&(e.facetDataEnabled=!1,e.facetPositions=[],e.facetNormals=[],e.facetPartitioning=new Array,e.facetParameters=null,e.depthSortedIndices=new Uint32Array(0)),this}updateIndices(e,t,i=!1){return this}createNormals(e){const t=this.getVerticesData(si.PositionKind),i=this.getIndices();let n;return n=this.isVerticesDataPresent(si.NormalKind)?this.getVerticesData(si.NormalKind):[],Ti.ComputeNormals(t,i,n,{useRightHandedSystem:this.getScene().useRightHandedSystem}),this.setVerticesData(si.NormalKind,n,e),this}alignWithNormal(e,t){t||(t=Ui.Y);const i=H.Vector3[0],n=H.Vector3[1];return B.CrossToRef(t,e,n),B.CrossToRef(e,n,i),this.rotationQuaternion?V.RotationQuaternionFromAxisToRef(i,e,n,this.rotationQuaternion):B.RotationFromAxisToRef(i,e,n,this.rotation),this}_checkOcclusionQuery(){return!1}disableEdgesRendering(){throw Y("EdgesRenderer")}enableEdgesRendering(e,t,i){throw Y("EdgesRenderer")}getConnectedParticleSystems(){return this._scene.particleSystems.filter((e=>e.emitter===this))}}Vi.OCCLUSION_TYPE_NONE=0,Vi.OCCLUSION_TYPE_OPTIMISTIC=1,Vi.OCCLUSION_TYPE_STRICT=2,Vi.OCCLUSION_ALGORITHM_TYPE_ACCURATE=0,Vi.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE=1,Vi.CULLINGSTRATEGY_STANDARD=Ze.MESHES_CULLINGSTRATEGY_STANDARD,Vi.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=Ze.MESHES_CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY,Vi.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=Ze.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION,Vi.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=Ze.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY,e([_.filter(((...[e,t,i,n,r])=>!(Array.isArray(e)||Array.isArray(t)||Array.isArray(i)||Array.isArray(n)||Array.isArray(r))))],Vi,"_ApplySkeleton",null),M("BABYLON.AbstractMesh",Vi);class ki{constructor(){this.reset()}reset(){this.enabled=!1,this.mask=255,this.func=Ze.ALWAYS,this.funcRef=1,this.funcMask=255,this.opStencilFail=Ze.KEEP,this.opDepthFail=Ze.KEEP,this.opStencilDepthPass=Ze.REPLACE}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){re.Clone((()=>e),this)}serialize(){return re.Serialize(this)}parse(e,t,i){re.Parse((()=>this),e,t,i)}}e([a()],ki.prototype,"func",null),e([a()],ki.prototype,"funcRef",null),e([a()],ki.prototype,"funcMask",null),e([a()],ki.prototype,"opStencilFail",null),e([a()],ki.prototype,"opDepthFail",null),e([a()],ki.prototype,"opStencilDepthPass",null),e([a()],ki.prototype,"mask",null),e([a()],ki.prototype,"enabled",null);class Xi{static CompareLightsPriority(e,t){return e.shadowEnabled!==t.shadowEnabled?(t.shadowEnabled?1:0)-(e.shadowEnabled?1:0):t.renderPriority-e.renderPriority}}function Hi(e,t,i){i&&e.setFloat4(t,i.normal.x,i.normal.y,i.normal.z,i.d)}Xi.FALLOFF_DEFAULT=0,Xi.FALLOFF_PHYSICAL=1,Xi.FALLOFF_GLTF=2,Xi.FALLOFF_STANDARD=3,Xi.LIGHTMAP_DEFAULT=0,Xi.LIGHTMAP_SPECULAR=1,Xi.LIGHTMAP_SHADOWSONLY=2,Xi.INTENSITYMODE_AUTOMATIC=0,Xi.INTENSITYMODE_LUMINOUSPOWER=1,Xi.INTENSITYMODE_LUMINOUSINTENSITY=2,Xi.INTENSITYMODE_ILLUMINANCE=3,Xi.INTENSITYMODE_LUMINANCE=4,Xi.LIGHTTYPEID_POINTLIGHT=0,Xi.LIGHTTYPEID_DIRECTIONALLIGHT=1,Xi.LIGHTTYPEID_SPOTLIGHT=2,Xi.LIGHTTYPEID_HEMISPHERICLIGHT=3;const Wi=ee.Black();function zi(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 Yi(e,t,i){const n=e.getTextureMatrix();t.updateMatrix(i+"Matrix",n)}function Ki(e,t,i,n,r,s=!0){e._bindLight(t,i,n,r,s)}function qi(e,t,i,n,r,s,a,o=!1){a._areMiscDirty&&(a.LOGARITHMICDEPTH=i,a.POINTSIZE=n,a.FOG=r&&function(e,t){return t.fogEnabled&&e.applyFog&&t.fogMode!==Ze.FOGMODE_NONE}(e,t),a.NONUNIFORMSCALING=e.nonUniformScaling,a.ALPHATEST=s,a.DECAL_AFTER_DETAIL=o)}function ji(e,t,i,n,r,s,a){switch(a.needNormals=!0,void 0===r["LIGHT"+n]&&(a.needRebuild=!0),r["LIGHT"+n]=!0,r["SPOTLIGHT"+n]=!1,r["HEMILIGHT"+n]=!1,r["POINTLIGHT"+n]=!1,r["DIRLIGHT"+n]=!1,i.prepareLightSpecificDefines(r,n),r["LIGHT_FALLOFF_PHYSICAL"+n]=!1,r["LIGHT_FALLOFF_GLTF"+n]=!1,r["LIGHT_FALLOFF_STANDARD"+n]=!1,i.falloffType){case Xi.FALLOFF_GLTF:r["LIGHT_FALLOFF_GLTF"+n]=!0;break;case Xi.FALLOFF_PHYSICAL:r["LIGHT_FALLOFF_PHYSICAL"+n]=!0;break;case Xi.FALLOFF_STANDARD:r["LIGHT_FALLOFF_STANDARD"+n]=!0}if(i.specular.equalsFloats(0,0,0)||(a.specularEnabled=!0),r["SHADOW"+n]=!1,r["SHADOWCSM"+n]=!1,r["SHADOWCSMDEBUG"+n]=!1,r["SHADOWCSMNUM_CASCADES"+n]=!1,r["SHADOWCSMUSESHADOWMAXZ"+n]=!1,r["SHADOWCSMNOBLEND"+n]=!1,r["SHADOWCSM_RIGHTHANDED"+n]=!1,r["SHADOWPCF"+n]=!1,r["SHADOWPCSS"+n]=!1,r["SHADOWPOISSON"+n]=!1,r["SHADOWESM"+n]=!1,r["SHADOWCLOSEESM"+n]=!1,r["SHADOWCUBE"+n]=!1,r["SHADOWLOWQUALITY"+n]=!1,r["SHADOWMEDIUMQUALITY"+n]=!1,t&&t.receiveShadows&&e.shadowsEnabled&&i.shadowEnabled){const t=i.getShadowGenerator(e.activeCamera)??i.getShadowGenerator();if(t){const e=t.getShadowMap();e&&e.renderList&&e.renderList.length>0&&(a.shadowEnabled=!0,t.prepareDefines(r,n))}}i.lightmapMode!=Xi.LIGHTMAP_DEFAULT?(a.lightmapMode=!0,r["LIGHTMAPEXCLUDED"+n]=!0,r["LIGHTMAPNOSPECULAR"+n]=i.lightmapMode==Xi.LIGHTMAP_SHADOWSONLY):(r["LIGHTMAPEXCLUDED"+n]=!1,r["LIGHTMAPNOSPECULAR"+n]=!1)}function Qi(e,t,i,n,r,s=null,a=!1){let o=function(e,t){let i=!1;if(e.activeCamera){const n=t.CAMERA_ORTHOGRAPHIC?1:0,r=t.CAMERA_PERSPECTIVE?1:0,s=e.activeCamera.mode===Ze.ORTHOGRAPHIC_CAMERA?1:0,a=e.activeCamera.mode===Ze.PERSPECTIVE_CAMERA?1:0;(n^s||r^a)&&(t.CAMERA_ORTHOGRAPHIC=1===s,t.CAMERA_PERSPECTIVE=1===a,i=!0)}return i}(e,n);!1!==s&&(o=function(e,t,i){let n=!1;const r=!!(e.clipPlane??t.clipPlane),s=!!(e.clipPlane2??t.clipPlane2),a=!!(e.clipPlane3??t.clipPlane3),o=!!(e.clipPlane4??t.clipPlane4),l=!!(e.clipPlane5??t.clipPlane5),c=!!(e.clipPlane6??t.clipPlane6);return i.CLIPPLANE!==r&&(i.CLIPPLANE=r,n=!0),i.CLIPPLANE2!==s&&(i.CLIPPLANE2=s,n=!0),i.CLIPPLANE3!==a&&(i.CLIPPLANE3=a,n=!0),i.CLIPPLANE4!==o&&(i.CLIPPLANE4=o,n=!0),i.CLIPPLANE5!==l&&(i.CLIPPLANE5=l,n=!0),i.CLIPPLANE6!==c&&(i.CLIPPLANE6=c,n=!0),n}(i,e,n)),n.DEPTHPREPASS!==!t.getColorWrite()&&(n.DEPTHPREPASS=!n.DEPTHPREPASS,o=!0),n.INSTANCES!==r&&(n.INSTANCES=r,o=!0),n.THIN_INSTANCES!==a&&(n.THIN_INSTANCES=a,o=!0),o&&n.markAsUnprocessed()}function Zi(e,t,i,n,r=null,s=!1){r&&r.push("Light"+e),s||(t.push("vLightData"+e,"vLightDiffuse"+e,"vLightSpecular"+e,"vLightDirection"+e,"vLightFalloff"+e,"vLightGround"+e,"lightMatrix"+e,"shadowsInfo"+e,"depthValues"+e),i.push("shadowTexture"+e),i.push("depthTexture"+e),t.push("viewFrustumZ"+e,"cascadeBlendFactor"+e,"lightSizeUVCorrection"+e,"depthCorrection"+e,"penumbraDarkness"+e,"frustumLengths"+e),n&&(i.push("projectionLightTexture"+e),t.push("textureProjectionMatrix"+e)))}class Ji{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(Ji.MiscDirtyFlag+Ji.PrePassDirtyFlag)}get alpha(){return this._alpha}set backFaceCulling(e){this._backFaceCulling!==e&&(this._backFaceCulling=e,this.markAsDirty(Ji.TextureDirtyFlag))}get backFaceCulling(){return this._backFaceCulling}set cullBackFaces(e){this._cullBackFaces!==e&&(this._cullBackFaces=e,this.markAsDirty(Ji.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 g),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 g),this._onUnBindObservable}get onEffectCreatedObservable(){return this._onEffectCreatedObservable||(this._onEffectCreatedObservable=new g),this._onEffectCreatedObservable}set alphaMode(e){this._alphaMode!==e&&(this._alphaMode=e,this.markAsDirty(Ji.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(Ji.MiscDirtyFlag))}get fogEnabled(){return this._fogEnabled}get wireframe(){switch(this._fillMode){case Ji.WireFrameFillMode:case Ji.LineListDrawMode:case Ji.LineLoopDrawMode:case Ji.LineStripDrawMode:return!0}return this._scene.forceWireframe}set wireframe(e){this.fillMode=e?Ji.WireFrameFillMode:Ji.TriangleFillMode}get pointsCloud(){switch(this._fillMode){case Ji.PointFillMode:case Ji.PointListDrawMode:return!0}return this._scene.forcePointsCloud}set pointsCloud(e){this.fillMode=e?Ji.PointFillMode:Ji.TriangleFillMode}get fillMode(){return this._fillMode}set fillMode(e){this._fillMode!==e&&(this._fillMode=e,this.markAsDirty(Ji.MiscDirtyFlag))}get useLogarithmicDepth(){return this._useLogarithmicDepth}set useLogarithmicDepth(e){const t=this.getScene().getEngine().getCaps().fragmentDepthSupported;e&&!t&&de.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){this.shadowDepthWrapper=null,this.allowShaderHotSwapping=!0,this._shaderLanguage=0,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 g,this._onDisposeObserver=null,this._onUnBindObservable=null,this._onBindObserver=null,this._alphaMode=Ze.ALPHA_COMBINE,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 ki,this._useUBO=!1,this._fillMode=Ji.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 n=t||y.LastCreatedScene;n&&(this._scene=n,this._dirtyCallbacks={},this._dirtyCallbacks[Ze.MATERIAL_TextureDirtyFlag]=this._markAllSubMeshesAsTexturesDirty.bind(this),this._dirtyCallbacks[Ze.MATERIAL_LightDirtyFlag]=this._markAllSubMeshesAsLightsDirty.bind(this),this._dirtyCallbacks[Ze.MATERIAL_FresnelDirtyFlag]=this._markAllSubMeshesAsFresnelDirty.bind(this),this._dirtyCallbacks[Ze.MATERIAL_AttributesDirtyFlag]=this._markAllSubMeshesAsAttributesDirty.bind(this),this._dirtyCallbacks[Ze.MATERIAL_MiscDirtyFlag]=this._markAllSubMeshesAsMiscDirty.bind(this),this._dirtyCallbacks[Ze.MATERIAL_PrePassDirtyFlag]=this._markAllSubMeshesAsPrePassDirty.bind(this),this._dirtyCallbacks[Ze.MATERIAL_AllDirtyFlag]=this._markAllSubMeshesAsAllDirty.bind(this),this.id=e||Yt.RandomId(),this.uniqueId=this._scene.getUniqueId(),this._materialContext=this._scene.getEngine().createMaterialContext(),this._drawWrapper=new pi(this._scene.getEngine(),!1),this._drawWrapper.materialContext=this._materialContext,this._uniformBuffer=new Pi(this._scene.getEngine(),void 0,void 0,e),this._useUBO=this.getScene().getEngine().supportsUniformBuffers,i||this._scene.addMaterial(this),this._scene.useMaterialMeshMap&&(this.meshMap={}),Ji.OnEventObservable.notifyObservers(this,1))}toString(e){return"Name: "+this.name}getClassName(){return"Material"}get _isMaterial(){return!0}get isFrozen(){return this.checkReadyOnlyOnce}freeze(){this.markDirty(),this.checkReadyOnlyOnce=!0}unfreeze(){this.markDirty(),this.checkReadyOnlyOnce=!1}isReady(e,t){return!0}isReadyForSubMesh(e,t,i){const n=t.materialDefines;return!!n&&(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=n,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),this._eventInfo.isReadyForSubMesh)}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===Ji.MATERIAL_ALPHATESTANDBLEND,this._markAllSubMeshesAsTexturesAndMiscDirty())}get _disableAlphaBlending(){return this._transparencyMode===Ji.MATERIAL_OPAQUE||this._transparencyMode===Ji.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(Ji.AllDirtyFlag)}_preBind(e,t=null){const i=this._scene.getEngine(),n=(null==t?this.sideOrientation:t)===Ji.ClockWiseSideOrientation;return i.enableEffect(e||this._getDrawWrapper()),i.setState(this.backFaceCulling,this.zOffset,!1,n,this._scene._mirroredCameraPosition?!this.cullBackFaces:this.cullBackFaces,this.stencil,this.zOffsetUnits),n}bind(e,t){}buildUniformLayout(){const e=this._uniformBuffer;this._eventInfo.ubo=e,this._callbackPluginEventGeneric(8,this._eventInfo),e.create(),this._uniformBufferLayoutBuilt=!0}bindForSubMesh(e,t,i){const n=i._drawWrapper;this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),n._forceRebindOnNextCall=!1}bindOnlyWorldMatrix(e){}bindView(e){this._useUBO?this._needToBindSceneUbo=!0:e.setMatrix("view",this.getScene().getViewMatrix())}bindViewProjection(e){this._useUBO?this._needToBindSceneUbo=!0:(e.setMatrix("viewProjection",this.getScene().getTransformMatrix()),e.setMatrix("projection",this.getScene().getProjectionMatrix()))}bindEyePosition(e,t){this._useUBO?this._needToBindSceneUbo=!0:this._scene.bindEyePosition(e,t)}_afterBind(e,t=null,i){if(this._scene._cachedMaterial=this,this._needToBindSceneUbo&&t&&(this._needToBindSceneUbo=!1,function(e,t){t.bindToEffect(e,"Scene")}(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(){if(this._onUnBindObservable&&this._onUnBindObservable.notifyObservers(this),0!==this.depthFunction){this._scene.getEngine().setDepthFunction(this._cachedDepthFunctionState)}if(this.disableDepthWrite){this._scene.getEngine().setDepthWrite(this._cachedDepthWriteState)}if(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),Ji._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,n){const r={clipPlane:!1,useInstances:!1,...i},s=this.getScene(),a=this.allowShaderHotSwapping;this.allowShaderHotSwapping=!1;const o=()=>{if(!this._scene||!this._scene.getEngine())return;const i=s.clipPlane;if(r.clipPlane&&(s.clipPlane=new ei(0,0,0,1)),this._storeEffectOnSubMeshes){let i=!0,s=null;if(e.subMeshes){const t=new gi(0,0,0,0,0,e,void 0,!1,!1);t.materialDefines&&(t.materialDefines._renderId=-1),this.isReadyForSubMesh(e,t,r.useInstances)||(t.effect&&t.effect.getCompilationError()&&t.effect.allFallbacksProcessed()?s=t.effect.getCompilationError():(i=!1,setTimeout(o,16)))}i&&(this.allowShaderHotSwapping=a,s&&n&&n(s),t&&t(this))}else this.isReady()?(this.allowShaderHotSwapping=a,t&&t(this)):setTimeout(o,16);r.clipPlane&&(s.clipPlane=i)};o()}forceCompilationAsync(e,t){return new Promise(((i,n)=>{this.forceCompilation(e,(()=>{i()}),t,(e=>{n(e)}))}))}markAsDirty(e){this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism||(Ji._DirtyCallbackArray.length=0,e&Ji.TextureDirtyFlag&&Ji._DirtyCallbackArray.push(Ji._TextureDirtyCallBack),e&Ji.LightDirtyFlag&&Ji._DirtyCallbackArray.push(Ji._LightsDirtyCallBack),e&Ji.FresnelDirtyFlag&&Ji._DirtyCallbackArray.push(Ji._FresnelDirtyCallBack),e&Ji.AttributesDirtyFlag&&Ji._DirtyCallbackArray.push(Ji._AttributeDirtyCallBack),e&Ji.MiscDirtyFlag&&Ji._DirtyCallbackArray.push(Ji._MiscDirtyCallBack),e&Ji.PrePassDirtyFlag&&Ji._DirtyCallbackArray.push(Ji._PrePassDirtyCallBack),Ji._DirtyCallbackArray.length&&this._markAllSubMeshesAsDirty(Ji._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(Ji._AllDirtyCallBack)}_markAllSubMeshesAsImageProcessingDirty(){this._markAllSubMeshesAsDirty(Ji._ImageProcessingDirtyCallBack)}_markAllSubMeshesAsTexturesDirty(){this._markAllSubMeshesAsDirty(Ji._TextureDirtyCallBack)}_markAllSubMeshesAsFresnelDirty(){this._markAllSubMeshesAsDirty(Ji._FresnelDirtyCallBack)}_markAllSubMeshesAsFresnelAndMiscDirty(){this._markAllSubMeshesAsDirty(Ji._FresnelAndMiscDirtyCallBack)}_markAllSubMeshesAsLightsDirty(){this._markAllSubMeshesAsDirty(Ji._LightsDirtyCallBack)}_markAllSubMeshesAsAttributesDirty(){this._markAllSubMeshesAsDirty(Ji._AttributeDirtyCallBack)}_markAllSubMeshesAsMiscDirty(){this._markAllSubMeshesAsDirty(Ji._MiscDirtyCallBack)}_markAllSubMeshesAsPrePassDirty(){this._markAllSubMeshesAsDirty(Ji._MiscDirtyCallBack)}_markAllSubMeshesAsTexturesAndMiscDirty(){this._markAllSubMeshesAsDirty(Ji._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 n=this.getScene();if(n.stopAnimation(this),n.freeProcessedMaterials(),n.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 t in this.meshMap){const i=this.meshMap[t];i&&(i.material=null,this.releaseVertexArrayObject(i,e))}else{const t=n.meshes;for(const i of t)i.material!==this||i.sourceMesh||(i.material=null,this.releaseVertexArrayObject(i,e))}this._uniformBuffer.dispose(),e&&this._drawWrapper.effect&&(this._storeEffectOnSubMeshes||this._drawWrapper.effect.dispose(),this._drawWrapper.effect=null),this.metadata=null,this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this._onBindObservable&&this._onBindObservable.clear(),this._onUnBindObservable&&this._onUnBindObservable.clear(),this._onEffectCreatedObservable&&this._onEffectCreatedObservable.clear(),this._eventInfo&&(this._eventInfo={})}releaseVertexArrayObject(e,t){const i=e.geometry;if(i)if(this._storeEffectOnSubMeshes){if(e.subMeshes)for(const n of e.subMeshes)i._releaseVertexArrayObject(n.effect),t&&n.effect&&n.effect.dispose()}else i._releaseVertexArrayObject(this._drawWrapper.effect)}serialize(){const e=re.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 de.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 n=Yt.Instantiate(e.customType).Parse(e,t,i);return n._loadedUniqueId=e.uniqueId,n}static _ParsePlugins(e,t,i,n){if(e.plugins)for(const r in e.plugins){const s=e.plugins[r];let a=t.pluginManager?.getPlugin(s.name);if(!a){const e=Yt.Instantiate("BABYLON."+r);e&&(a=new e(t))}a?.parse(s,i,n)}}}Ji.TriangleFillMode=Ze.MATERIAL_TriangleFillMode,Ji.WireFrameFillMode=Ze.MATERIAL_WireFrameFillMode,Ji.PointFillMode=Ze.MATERIAL_PointFillMode,Ji.PointListDrawMode=Ze.MATERIAL_PointListDrawMode,Ji.LineListDrawMode=Ze.MATERIAL_LineListDrawMode,Ji.LineLoopDrawMode=Ze.MATERIAL_LineLoopDrawMode,Ji.LineStripDrawMode=Ze.MATERIAL_LineStripDrawMode,Ji.TriangleStripDrawMode=Ze.MATERIAL_TriangleStripDrawMode,Ji.TriangleFanDrawMode=Ze.MATERIAL_TriangleFanDrawMode,Ji.ClockWiseSideOrientation=Ze.MATERIAL_ClockWiseSideOrientation,Ji.CounterClockWiseSideOrientation=Ze.MATERIAL_CounterClockWiseSideOrientation,Ji.TextureDirtyFlag=Ze.MATERIAL_TextureDirtyFlag,Ji.LightDirtyFlag=Ze.MATERIAL_LightDirtyFlag,Ji.FresnelDirtyFlag=Ze.MATERIAL_FresnelDirtyFlag,Ji.AttributesDirtyFlag=Ze.MATERIAL_AttributesDirtyFlag,Ji.MiscDirtyFlag=Ze.MATERIAL_MiscDirtyFlag,Ji.PrePassDirtyFlag=Ze.MATERIAL_PrePassDirtyFlag,Ji.AllDirtyFlag=Ze.MATERIAL_AllDirtyFlag,Ji.MATERIAL_OPAQUE=0,Ji.MATERIAL_ALPHATEST=1,Ji.MATERIAL_ALPHABLEND=2,Ji.MATERIAL_ALPHATESTANDBLEND=3,Ji.MATERIAL_NORMALBLENDMETHOD_WHITEOUT=0,Ji.MATERIAL_NORMALBLENDMETHOD_RNM=1,Ji.OnEventObservable=new g,Ji._AllDirtyCallBack=e=>e.markAllAsDirty(),Ji._ImageProcessingDirtyCallBack=e=>e.markAsImageProcessingDirty(),Ji._TextureDirtyCallBack=e=>e.markAsTexturesDirty(),Ji._FresnelDirtyCallBack=e=>e.markAsFresnelDirty(),Ji._MiscDirtyCallBack=e=>e.markAsMiscDirty(),Ji._PrePassDirtyCallBack=e=>e.markAsPrePassDirty(),Ji._LightsDirtyCallBack=e=>e.markAsLightDirty(),Ji._AttributeDirtyCallBack=e=>e.markAsAttributesDirty(),Ji._FresnelAndMiscDirtyCallBack=e=>{Ji._FresnelDirtyCallBack(e),Ji._MiscDirtyCallBack(e)},Ji._TextureAndMiscDirtyCallBack=e=>{Ji._TextureDirtyCallBack(e),Ji._MiscDirtyCallBack(e)},Ji._DirtyCallbackArray=[],Ji._RunDirtyCallBacks=e=>{for(const t of Ji._DirtyCallbackArray)t(e)},e([a()],Ji.prototype,"id",void 0),e([a()],Ji.prototype,"uniqueId",void 0),e([a()],Ji.prototype,"name",void 0),e([a()],Ji.prototype,"metadata",void 0),e([a()],Ji.prototype,"checkReadyOnEveryCall",void 0),e([a()],Ji.prototype,"checkReadyOnlyOnce",void 0),e([a()],Ji.prototype,"state",void 0),e([a("alpha")],Ji.prototype,"_alpha",void 0),e([a("backFaceCulling")],Ji.prototype,"_backFaceCulling",void 0),e([a("cullBackFaces")],Ji.prototype,"_cullBackFaces",void 0),e([a()],Ji.prototype,"sideOrientation",void 0),e([a("alphaMode")],Ji.prototype,"_alphaMode",void 0),e([a()],Ji.prototype,"_needDepthPrePass",void 0),e([a()],Ji.prototype,"disableDepthWrite",void 0),e([a()],Ji.prototype,"disableColorWrite",void 0),e([a()],Ji.prototype,"forceDepthWrite",void 0),e([a()],Ji.prototype,"depthFunction",void 0),e([a()],Ji.prototype,"separateCullingPass",void 0),e([a("fogEnabled")],Ji.prototype,"_fogEnabled",void 0),e([a()],Ji.prototype,"pointSize",void 0),e([a()],Ji.prototype,"zOffset",void 0),e([a()],Ji.prototype,"zOffsetUnits",void 0),e([a()],Ji.prototype,"pointsCloud",null),e([a()],Ji.prototype,"fillMode",null),e([a()],Ji.prototype,"useLogarithmicDepth",null),e([a()],Ji.prototype,"transparencyMode",null);class $i extends Ji{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 n=t.apply(e,i);return this._markAllSubMeshesAsTexturesDirty(),n};const i=e.splice;e.splice=(t,n)=>{const r=i.apply(e,[t,n]);return this._markAllSubMeshesAsTexturesDirty(),r}}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<this.subMaterials.length;t++)if(this.subMaterials[t]?.hasTexture(e))return!0;return!1}getClassName(){return"MultiMaterial"}isReadyForSubMesh(e,t,i){for(let n=0;n<this.subMaterials.length;n++){const r=this.subMaterials[n];if(r){if(r._storeEffectOnSubMeshes){if(!r.isReadyForSubMesh(e,t,i))return!1;continue}if(!r.isReady(e))return!1}}return!0}clone(e,t){const i=new $i(e,this.getScene());for(let n=0;n<this.subMaterials.length;n++){let r=null;const s=this.subMaterials[n];r=t&&s?s.clone(e+"-"+s.name):this.subMaterials[n],i.subMaterials.push(r)}return i}serialize(){const e={};e.name=this.name,e.id=this.id,e.uniqueId=this.uniqueId,q&&(e.tags=q.GetTags(this)),e.materialsUniqueIds=[],e.materials=[];for(let t=0;t<this.subMaterials.length;t++){const i=this.subMaterials[t];i?(e.materialsUniqueIds.push(i.uniqueId),e.materials.push(i.id)):(e.materialsUniqueIds.push(null),e.materials.push(null))}return e}dispose(e,t,i){const n=this.getScene();if(!n)return;if(i)for(let i=0;i<this.subMaterials.length;i++){const n=this.subMaterials[i];n&&n.dispose(e,t)}const r=n.multiMaterials.indexOf(this);r>=0&&n.multiMaterials.splice(r,1),super.dispose(e,t)}static ParseMultiMaterial(e,t){const i=new $i(e.name,t);return i.id=e.id,i._loadedUniqueId=e.uniqueId,q&&q.AddTagsTo(i,e.tags),e.materialsUniqueIds?i._waitingSubMaterialsUniqueIds=e.materialsUniqueIds:e.materials.forEach((e=>i.subMaterials.push(t.getLastMaterialById(e)))),i}}M("BABYLON.MultiMaterial",$i);class en{}en.NAME_EFFECTLAYER="EffectLayer",en.NAME_LAYER="Layer",en.NAME_LENSFLARESYSTEM="LensFlareSystem",en.NAME_BOUNDINGBOXRENDERER="BoundingBoxRenderer",en.NAME_PARTICLESYSTEM="ParticleSystem",en.NAME_GAMEPAD="Gamepad",en.NAME_SIMPLIFICATIONQUEUE="SimplificationQueue",en.NAME_GEOMETRYBUFFERRENDERER="GeometryBufferRenderer",en.NAME_PREPASSRENDERER="PrePassRenderer",en.NAME_DEPTHRENDERER="DepthRenderer",en.NAME_DEPTHPEELINGRENDERER="DepthPeelingRenderer",en.NAME_POSTPROCESSRENDERPIPELINEMANAGER="PostProcessRenderPipelineManager",en.NAME_SPRITE="Sprite",en.NAME_SUBSURFACE="SubSurface",en.NAME_OUTLINERENDERER="Outline",en.NAME_PROCEDURALTEXTURE="ProceduralTexture",en.NAME_SHADOWGENERATOR="ShadowGenerator",en.NAME_OCTREE="Octree",en.NAME_PHYSICSENGINE="PhysicsEngine",en.NAME_AUDIO="Audio",en.NAME_FLUIDRENDERER="FluidRenderer",en.STEP_ISREADYFORMESH_EFFECTLAYER=0,en.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER=0,en.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER=0,en.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER=0,en.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER=1,en.STEP_BEFORECAMERADRAW_PREPASS=0,en.STEP_BEFORECAMERADRAW_EFFECTLAYER=1,en.STEP_BEFORECAMERADRAW_LAYER=2,en.STEP_BEFORERENDERTARGETDRAW_PREPASS=0,en.STEP_BEFORERENDERTARGETDRAW_LAYER=1,en.STEP_BEFORERENDERINGMESH_PREPASS=0,en.STEP_BEFORERENDERINGMESH_OUTLINE=1,en.STEP_AFTERRENDERINGMESH_PREPASS=0,en.STEP_AFTERRENDERINGMESH_OUTLINE=1,en.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW=0,en.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER=1,en.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE=0,en.STEP_BEFORECAMERAUPDATE_GAMEPAD=1,en.STEP_BEFORECLEAR_PROCEDURALTEXTURE=0,en.STEP_BEFORECLEAR_PREPASS=1,en.STEP_BEFORERENDERTARGETCLEAR_PREPASS=0,en.STEP_AFTERRENDERTARGETDRAW_PREPASS=0,en.STEP_AFTERRENDERTARGETDRAW_LAYER=1,en.STEP_AFTERCAMERADRAW_PREPASS=0,en.STEP_AFTERCAMERADRAW_EFFECTLAYER=1,en.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM=2,en.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW=3,en.STEP_AFTERCAMERADRAW_LAYER=4,en.STEP_AFTERCAMERADRAW_FLUIDRENDERER=5,en.STEP_AFTERCAMERAPOSTPROCESS_LAYER=0,en.STEP_AFTERRENDERTARGETPOSTPROCESS_LAYER=0,en.STEP_AFTERRENDER_AUDIO=0,en.STEP_GATHERRENDERTARGETS_DEPTHRENDERER=0,en.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER=1,en.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR=2,en.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER=3,en.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER=0,en.STEP_GATHERACTIVECAMERARENDERTARGETS_FLUIDRENDERER=1,en.STEP_POINTERMOVE_SPRITE=0,en.STEP_POINTERDOWN_SPRITE=0,en.STEP_POINTERUP_SPRITE=0;class tn extends Array{constructor(e){super(...e)}static Create(){return Object.create(tn.prototype)}registerStep(e,t,i){let n=0,r=Number.MAX_VALUE;for(;n<this.length;n++){if(r=this[n].index,e<r)break}this.splice(n,0,{index:e,component:t,action:i.bind(t)})}clear(){this.length=0}}class nn{constructor(e,t){this.distanceOrScreenCoverage=e,this.mesh=t}}class rn{constructor(){this.visibleInstances={},this.batchCache=new sn,this.batchCacheReplacementModeInFrozenMode=new sn,this.instancesBufferSize=2048}}class sn{constructor(){this.mustReturn=!1,this.visibleInstances=new Array,this.renderSelf=[],this.hardwareInstancedRendering=[]}}class an{constructor(){this.instancesCount=0,this.matrixBuffer=null,this.previousMatrixBuffer=null,this.matrixBufferSize=512,this.matrixData=null,this.boundingVectors=[],this.worldMatrices=null}}class on{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 ln extends Vi{static _GetDefaultSideOrientation(e){return e||ln.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(si.PositionKind,this._internalMeshDataInfo._sourcePositions,!0),this._internalMeshDataInfo._sourceNormals&&this.setVerticesData(si.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 g),this._internalMeshDataInfo._onBeforeRenderObservable}get onBeforeBindObservable(){return this._internalMeshDataInfo._onBeforeBindObservable||(this._internalMeshDataInfo._onBeforeBindObservable=new g),this._internalMeshDataInfo._onBeforeBindObservable}get onAfterRenderObservable(){return this._internalMeshDataInfo._onAfterRenderObservable||(this._internalMeshDataInfo._onAfterRenderObservable=new g),this._internalMeshDataInfo._onAfterRenderObservable}get onBetweenPassObservable(){return this._internalMeshDataInfo._onBetweenPassObservable||(this._internalMeshDataInfo._onBetweenPassObservable=new g),this._internalMeshDataInfo._onBetweenPassObservable}get onBeforeDrawObservable(){return this._internalMeshDataInfo._onBeforeDrawObservable||(this._internalMeshDataInfo._onBeforeDrawObservable=new g),this._internalMeshDataInfo._onBeforeDrawObservable}set onBeforeDraw(e){this._onBeforeDrawObserver&&this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver),this._onBeforeDrawObserver=this.onBeforeDrawObservable.add(e)}get hasInstances(){return this.instances.length>0}get hasThinInstances(){return(this.forcedInstanceCount||this._thinInstanceDataStorage.instancesCount||0)>0}get forcedInstanceCount(){return this._internalMeshDataInfo._forcedInstanceCount}set forcedInstanceCount(e){this._internalMeshDataInfo._forcedInstanceCount=e}get sideOrientation(){return this._internalMeshDataInfo._sideOrientation}set sideOrientation(e){this._internalMeshDataInfo._sideOrientation=e,this._internalAbstractMeshDataInfo._sideOrientationHint=this._scene.useRightHandedSystem&&e===Ze.MATERIAL_CounterClockWiseSideOrientation||!this._scene.useRightHandedSystem&&e===Ze.MATERIAL_ClockWiseSideOrientation}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 n=this.getScene();if(e._geometry&&e._geometry.applyToMesh(this),fe.DeepCopy(e,this,["name","material","skeleton","instances","parent","uniqueId","source","metadata","morphTargetManager","hasInstances","worldMatrixInstancedBuffer","previousWorldMatrixInstancedBuffer","hasLODLevels","geometry","isBlocked","areNormalsFrozen","facetNb","isFacetDataEnabled","lightSources","useBones","isAnInstance","collider","edgesRenderer","forward","up","right","absolutePosition","absoluteScaling","absoluteRotationQuaternion","isWorldMatrixFrozen","nonUniformScaling","behaviors","worldMatrixFromCache","hasThinInstances","cloneMeshMap","hasBoundingInfo","physicsBody","physicsImpostor"],["_poseMatrix"]),this._internalMeshDataInfo._source=e,n.useClonedMeshMap&&(e._internalMeshDataInfo.meshMap||(e._internalMeshDataInfo.meshMap={}),e._internalMeshDataInfo.meshMap[this.uniqueId]=this),this._originalBuilderSideOrientation=e._originalBuilderSideOrientation,this._creationDataStorage=e._creationDataStorage,e._ranges){const 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,q&&q.HasTags(e)&&q.AddTagsTo(this,q.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<t.length;e++){const i=t[e];i.clone&&i.clone(this.name+"."+i.name,this)}}if(e.morphTargetManager&&(this.morphTargetManager=e.morphTargetManager),n.getPhysicsEngine){const t=n.getPhysicsEngine();if(i&&t)if(1===t.getPluginVersion()){const i=t.getImpostorForPhysicsObject(e);i&&(this.physicsImpostor=i.clone(this))}else 2===t.getPluginVersion()&&e.physicsBody&&e.physicsBody.clone(this)}for(let t=0;t<n.particleSystems.length;t++){const i=n.particleSystems[t];i.emitter===e&&i.clone(i.name,this)}this.skeleton=e.skeleton,this.refreshBoundingInfo(!0,!0),this.computeWorldMatrix(!0)}constructor(e,t=null,i=null,n=null,r,s=!0){super(e,t),this._internalMeshDataInfo=new on,this.delayLoadState=Ze.DELAYLOADSTATE_NONE,this.instances=[],this._creationDataStorage=null,this._geometry=null,this._instanceDataStorage=new rn,this._thinInstanceDataStorage=new an,this._shouldGenerateFlatShading=!1,this._originalBuilderSideOrientation=ln.DEFAULTSIDE,this.ignoreCameraMaxZ=!1,t=this.getScene(),this._scene.useRightHandedSystem?this.sideOrientation=Ze.MATERIAL_ClockWiseSideOrientation:this.sideOrientation=Ze.MATERIAL_CounterClockWiseSideOrientation,this._onBeforeDraw=(e,t,i)=>{e&&i&&(this._uniformBuffer?this.transferToEffect(t):i.bindOnlyWorldMatrix(t))},n&&this._copySource(n,r,s),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 g(this._internalMeshDataInfo._onMeshReadyObserverAdded),n&&n.onClonedObservable.notifyObservers(this)}instantiateHierarchy(e=null,t,i){const n=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));n.parent=e||this.parent,n.position=this.position.clone(),n.scaling=this.scaling.clone(),this.rotationQuaternion?n.rotationQuaternion=this.rotationQuaternion.clone():n.rotation=this.rotation.clone(),i&&i(this,n);for(const e of this.getChildTransformNodes(!0))"InstancedMesh"===e.getClassName()&&"Mesh"===n.getClassName()&&e.sourceMesh===this?e.instantiateHierarchy(n,{doNotInstantiate:t&&t.doNotInstantiate||!1,newSourcedMesh:n},i):e.instantiateHierarchy(n,t,i);return n}getClassName(){return"Mesh"}get _isMesh(){return!0}toString(e){let t=super.toString(e);if(t+=", n vertices: "+this.getTotalVertices(),t+=", parent: "+(this._waitingParentId?this._waitingParentId:this.parent?this.parent.name:"NONE"),this.animations)for(let i=0;i<this.animations.length;i++)t+=", animation[0]: "+this.animations[i].toString(e);if(e)if(this._geometry){const e=this.getIndices(),i=this.getVerticesData(si.PositionKind);i&&e&&(t+=", flat shading: "+(i.length/3===e.length?"YES":"NO"))}else t+=", flat shading: UNKNOWN";return t}_unBindEffect(){super._unBindEffect();for(const e of this.instances)e._unBindEffect()}get hasLODLevels(){return this._internalMeshDataInfo._LODLevels.length>0}getLODLevels(){return this._internalMeshDataInfo._LODLevels}_sortLODLevels(){const e=this._internalMeshDataInfo._useLODScreenCoverage?-1:1;this._internalMeshDataInfo._LODLevels.sort(((t,i)=>t.distanceOrScreenCoverage<i.distanceOrScreenCoverage?e:t.distanceOrScreenCoverage>i.distanceOrScreenCoverage?-e:0))}addLODLevel(e,t){if(t&&t._masterMesh)return de.Warn("You cannot use a mesh as LOD level twice"),this;const i=new nn(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;i<t._LODLevels.length;i++){const n=t._LODLevels[i];if(n.distanceOrScreenCoverage===e)return n.mesh}return null}removeLODLevel(e){const t=this._internalMeshDataInfo;for(let i=0;i<t._LODLevels.length;i++)t._LODLevels[i].mesh===e&&(t._LODLevels.splice(i,1),e&&(e._masterMesh=null));return this._sortLODLevels(),this}getLOD(e,t){const i=this._internalMeshDataInfo;if(!i._LODLevels||0===i._LODLevels.length)return this;const n=t||this.getBoundingInfo().boundingSphere,r=e.mode===ii.ORTHOGRAPHIC_CAMERA?e.minZ:n.centerWorld.subtract(e.globalPosition).length();let s=r,a=1;if(i._useLODScreenCoverage){const t=e.screenArea;let i=n.radiusWorld*e.minZ/r;i=i*i*Math.PI,s=i/t,a=-1}if(a*i._LODLevels[i._LODLevels.length-1].distanceOrScreenCoverage>a*s)return this.onLODLevelSelection&&this.onLODLevelSelection(s,this,this),this;for(let e=0;e<i._LODLevels.length;e++){const t=i._LODLevels[e];if(a*t.distanceOrScreenCoverage<a*s){if(t.mesh){if(t.mesh.delayLoadState===Ze.DELAYLOADSTATE_NOTLOADED)return t.mesh._checkDelayState(),this;if(t.mesh.delayLoadState===Ze.DELAYLOADSTATE_LOADING)return this;t.mesh._preActivate(),t.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache)}return this.onLODLevelSelection&&this.onLODLevelSelection(s,this,t.mesh),t.mesh}}return this.onLODLevelSelection&&this.onLODLevelSelection(s,this,this),this}get geometry(){return this._geometry}getTotalVertices(){return null===this._geometry||void 0===this._geometry?0:this._geometry.getTotalVertices()}getVerticesData(e,t,i,n){if(!this._geometry)return null;let r=n?void 0:this._userInstancedBuffersStorage?.vertexBuffers[e]?.getFloatData(this.instances.length+1,i||t&&1!==this._geometry.meshes.length);return r||(r=this._geometry.getVerticesData(e,t,i)),r}copyVerticesData(e,t){this._geometry&&this._geometry.copyVerticesData(e,t)}getVertexBuffer(e,t){return this._geometry?(t?void 0:this._userInstancedBuffersStorage?.vertexBuffers[e])??this._geometry.getVertexBuffer(e):null}isVerticesDataPresent(e,t){return this._geometry?!t&&void 0!==this._userInstancedBuffersStorage?.vertexBuffers[e]||this._geometry.isVerticesDataPresent(e):!!this._delayInfo&&-1!==this._delayInfo.indexOf(e)}isVertexBufferUpdatable(e,t){if(!this._geometry)return!!this._delayInfo&&-1!==this._delayInfo.indexOf(e);if(!t){const t=this._userInstancedBuffersStorage?.vertexBuffers[e];if(t)return t.isUpdatable()}return this._geometry.isVertexBufferUpdatable(e)}getVerticesDataKinds(e){if(!this._geometry){const e=[];return this._delayInfo&&this._delayInfo.forEach((function(t){e.push(t)})),e}const t=this._geometry.getVerticesDataKinds();if(!e&&this._userInstancedBuffersStorage)for(const e in this._userInstancedBuffersStorage.vertexBuffers)-1===t.indexOf(e)&&t.push(e);return t}getTotalIndices(){return this._geometry?this._geometry.getTotalIndices():0}getIndices(e,t){return this._geometry?this._geometry.getIndices(e,t):[]}get isBlocked(){return null!==this._masterMesh&&void 0!==this._masterMesh}isReady(e=!1,t=!1){if(this.delayLoadState===Ze.DELAYLOADSTATE_LOADING)return!1;if(!super.isReady(e))return!1;if(!this.subMeshes||0===this.subMeshes.length)return!0;if(!e)return!0;const i=this.getEngine(),n=this.getScene(),r=t||i.getCaps().instancedArrays&&(this.instances.length>0||this.hasThinInstances);this.computeWorldMatrix();const s=this.material||n.defaultMaterial;if(s)if(s._storeEffectOnSubMeshes)for(const e of this.subMeshes){const t=e.getMaterial();if(t)if(t._storeEffectOnSubMeshes){if(!t.isReadyForSubMesh(this,e,r))return!1}else if(!t.isReady(this,r))return!1}else if(!s.isReady(this,r))return!1;const a=i.currentRenderPassId;for(const e of this.lightSources){const t=e.getShadowGenerators();if(!t)continue;const n=t.values();for(let e=n.next();!0!==e.done;e=n.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 n=0;n<e.length;++n){i.currentRenderPassId=e[n];for(const e of this.subMeshes)if(!t.isReady(e,r,e.getMaterial()?.needAlphaBlendingForMesh(this)??!1))return i.currentRenderPassId=a,!1}i.currentRenderPassId=a}}}for(const e of this._internalMeshDataInfo._LODLevels)if(e.mesh&&!e.mesh.isReady(r))return!1;return!0}get areNormalsFrozen(){return this._internalMeshDataInfo._areNormalsFrozen}freezeNormals(){return this._internalMeshDataInfo._areNormalsFrozen=!0,this}unfreezeNormals(){return this._internalMeshDataInfo._areNormalsFrozen=!1,this}set overridenInstanceCount(e){this._instanceDataStorage.overridenInstanceCount=e}_preActivate(){const e=this._internalMeshDataInfo,t=this.getScene().getRenderId();return e._preActivateId===t||(e._preActivateId=t,this._instanceDataStorage.visibleInstances=null),this}_preActivateForIntermediateRendering(e){return this._instanceDataStorage.visibleInstances&&(this._instanceDataStorage.visibleInstances.intermediateDefaultRenderId=e),this}_registerInstanceForRenderId(e,t){return this._instanceDataStorage.visibleInstances||(this._instanceDataStorage.visibleInstances={defaultRenderId:t,selfDefaultRenderId:this._renderId}),this._instanceDataStorage.visibleInstances[t]||(void 0!==this._instanceDataStorage.previousRenderId&&this._instanceDataStorage.isFrozen&&(this._instanceDataStorage.visibleInstances[this._instanceDataStorage.previousRenderId]=null),this._instanceDataStorage.previousRenderId=t,this._instanceDataStorage.visibleInstances[t]=new Array),this._instanceDataStorage.visibleInstances[t].push(e),this}_afterComputeWorldMatrix(){super._afterComputeWorldMatrix(),this.hasThinInstances&&(this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1))}_postActivate(){this.edgesShareWithInstances&&this.edgesRenderer&&this.edgesRenderer.isEnabled&&this._renderingGroup&&(this._renderingGroup._edgesRenderers.pushNoDuplicate(this.edgesRenderer),this.edgesRenderer.customInstances.push(this.getWorldMatrix()))}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 n=this.geometry?this.geometry.boundingBias:null;return this._refreshBoundingInfo(this._getData(i,null,si.PositionKind),n),this}_createGlobalSubMesh(e){const t=this.getTotalVertices();if(!t||!this.getIndices())return null;if(this.subMeshes&&this.subMeshes.length>0){const i=this.getIndices();if(!i)return null;const n=i.length;let r=!1;if(e)r=!0;else for(const e of this.subMeshes){if(e.indexStart+e.indexCount>n){r=!0;break}if(e.verticesStart+e.verticesCount>t){r=!0;break}}if(!r)return this.subMeshes[0]}return this.releaseSubMeshes(),new gi(0,0,t,0,this.getTotalIndices(),this)}subdivide(e){if(e<1)return;const t=this.getTotalIndices();let i=t/e|0,n=0;for(;i%3!=0;)i++;this.releaseSubMeshes();for(let r=0;r<e&&!(n>=t);r++)gi.CreateFromIndices(0,n,r===e-1?t-n:i,this,void 0,!1),n+=i;this.refreshBoundingInfo(),this.synchronizeInstances()}setVerticesData(e,t,i=!1,n){if(this._geometry)this._geometry.setVerticesData(e,t,i,n);else{const n=new Ti;n.set(t,e);const r=this.getScene();new vi(vi.RandomId(),r,n,i,this)}return this}removeVerticesData(e){this._geometry&&this._geometry.removeVerticesData(e)}markVerticesDataAsUpdatable(e,t=!0){const i=this.getVertexBuffer(e);i&&i.isUpdatable()!==t&&this.setVerticesData(e,this.getVerticesData(e),t)}setVerticesBuffer(e,t=!0){return this._geometry||(this._geometry=vi.CreateGeometryForMesh(this)),this._geometry.setVerticesBuffer(e,null,t),this}updateVerticesData(e,t,i,n){return this._geometry?(n?(this.makeGeometryUnique(),this.updateVerticesData(e,t,i,!1)):this._geometry.updateVerticesData(e,t,i),this):this}updateMeshPositions(e,t=!0){const i=this.getVerticesData(si.PositionKind);if(!i)return this;if(e(i),this.updateVerticesData(si.PositionKind,i,!1,!1),t){const e=this.getIndices(),t=this.getVerticesData(si.NormalKind);if(!t)return this;Ti.ComputeNormals(i,e,t),this.updateVerticesData(si.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(vi.RandomId());return e.releaseForMesh(this,!0),t.applyToMesh(this),this}setIndexBuffer(e,t,i){let n=this._geometry;n||(n=new vi(vi.RandomId(),this.getScene(),void 0,void 0,this)),n.setIndexBuffer(e,t,i)}setIndices(e,t=null,i=!1){if(this._geometry)this._geometry.setIndices(e,t,i);else{const t=new Ti;t.indices=e;const n=this.getScene();new vi(vi.RandomId(),n,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,n=!0){if(!this._geometry)return this;const r=this.getScene().getEngine();let s;if(this._unIndexed)s=null;else switch(this._getRenderingFillMode(i)){case Ji.PointFillMode:s=null;break;case Ji.WireFrameFillMode:s=e._getLinesIndexBuffer(this.getIndices(),r);break;default:case Ji.TriangleFillMode:s=this._geometry.getIndexBuffer()}return this._bindDirect(t,s,n)}_bindDirect(e,t,i=!0){return this._geometry?(this.morphTargetManager&&this.morphTargetManager.isUsingTextureForTargets&&this.morphTargetManager._bind(e),i&&this._userInstancedBuffersStorage&&!this.hasThinInstances?this._geometry._bind(e,t,this._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 n=this.getScene().getEngine();return this._unIndexed||t==Ji.PointFillMode?n.drawArraysType(t,e.verticesStart,e.verticesCount,this.forcedInstanceCount||i):t==Ji.WireFrameFillMode?n.drawElementsType(t,0,e._linesIndexCount,this.forcedInstanceCount||i):n.drawElementsType(t,e.indexStart,e.indexCount,this.forcedInstanceCount||i),this}registerBeforeRender(e){return this.onBeforeRenderObservable.add(e),this}unregisterBeforeRender(e){return this.onBeforeRenderObservable.removeCallback(e),this}registerAfterRender(e){return this.onAfterRenderObservable.add(e),this}unregisterAfterRender(e){return this.onAfterRenderObservable.removeCallback(e),this}_getInstancesRenderList(e,t=!1){if(this._instanceDataStorage.isFrozen){if(t)return this._instanceDataStorage.batchCacheReplacementModeInFrozenMode.hardwareInstancedRendering[e]=!1,this._instanceDataStorage.batchCacheReplacementModeInFrozenMode.renderSelf[e]=!0,this._instanceDataStorage.batchCacheReplacementModeInFrozenMode;if(this._instanceDataStorage.previousBatch)return this._instanceDataStorage.previousBatch}const i=this.getScene(),n=i._isInIntermediateRendering(),r=n?this._internalAbstractMeshDataInfo._onlyForInstancesIntermediate:this._internalAbstractMeshDataInfo._onlyForInstances,s=this._instanceDataStorage.batchCache;if(s.mustReturn=!1,s.renderSelf[e]=t||!r&&this.isEnabled()&&this.isVisible,s.visibleInstances[e]=null,this._instanceDataStorage.visibleInstances&&!t){const t=this._instanceDataStorage.visibleInstances,r=i.getRenderId(),a=n?t.intermediateDefaultRenderId:t.defaultRenderId;s.visibleInstances[e]=t[r],!s.visibleInstances[e]&&a&&(s.visibleInstances[e]=t[a])}return s.hardwareInstancedRendering[e]=!t&&this._instanceDataStorage.hardwareInstancedRendering&&null!==s.visibleInstances[e]&&void 0!==s.visibleInstances[e],this._instanceDataStorage.previousBatch=s,s}_renderWithInstances(e,t,i,n,r){const s=i.visibleInstances[e._id],a=s?s.length:0,o=this._instanceDataStorage,l=o.instancesBufferSize;let c=o.instancesBuffer,h=o.instancesPreviousBuffer;const d=16*(a+1)*4;for(;o.instancesBufferSize<d;)o.instancesBufferSize*=2;o.instancesData&&l==o.instancesBufferSize||(o.instancesData=new Float32Array(o.instancesBufferSize/4)),(this._scene.needsPreviousWorldMatrices&&!o.instancesPreviousData||l!=o.instancesBufferSize)&&(o.instancesPreviousData=new Float32Array(o.instancesBufferSize/4));let u=0,f=0;const _=i.renderSelf[e._id],m=!c||l!==o.instancesBufferSize||this._scene.needsPreviousWorldMatrices&&!o.instancesPreviousBuffer;if(this._instanceDataStorage.manualUpdate||o.isFrozen&&!m)f=(_?1:0)+a;else{const t=this.getWorldMatrix();if(_&&(this._scene.needsPreviousWorldMatrices&&(o.masterMeshPreviousWorldMatrix?(o.masterMeshPreviousWorldMatrix.copyToArray(o.instancesPreviousData,u),o.masterMeshPreviousWorldMatrix.copyFrom(t)):(o.masterMeshPreviousWorldMatrix=t.clone(),o.masterMeshPreviousWorldMatrix.copyToArray(o.instancesPreviousData,u))),t.copyToArray(o.instancesData,u),u+=16,f++),s){if(ln.INSTANCEDMESH_SORT_TRANSPARENT&&this._scene.activeCamera&&e.getMaterial()?.needAlphaBlendingForMesh(e.getRenderingMesh())){const e=this._scene.activeCamera.globalPosition;for(let t=0;t<s.length;t++){const i=s[t];i._distanceToCamera=B.Distance(i.getBoundingInfo().boundingSphere.centerWorld,e)}s.sort(((e,t)=>e._distanceToCamera>t._distanceToCamera?-1:e._distanceToCamera<t._distanceToCamera?1:0))}for(let e=0;e<s.length;e++){const t=s[e],i=t.getWorldMatrix();i.copyToArray(o.instancesData,u),this._scene.needsPreviousWorldMatrices&&(t._previousWorldMatrix?(t._previousWorldMatrix.copyToArray(o.instancesPreviousData,u),t._previousWorldMatrix.copyFrom(i)):(t._previousWorldMatrix=i.clone(),t._previousWorldMatrix.copyToArray(o.instancesPreviousData,u))),u+=16,f++}}}return m?(c&&c.dispose(),h&&h.dispose(),c=new ri(r,o.instancesData,!0,16,!1,!0),o.instancesBuffer=c,this._userInstancedBuffersStorage||(this._userInstancedBuffersStorage={data:{},vertexBuffers:{},strides:{},sizes:{},vertexArrayObjects:this.getEngine().getCaps().vertexArrayObject?{}:void 0}),this._userInstancedBuffersStorage.vertexBuffers.world0=c.createVertexBuffer("world0",0,4),this._userInstancedBuffersStorage.vertexBuffers.world1=c.createVertexBuffer("world1",4,4),this._userInstancedBuffersStorage.vertexBuffers.world2=c.createVertexBuffer("world2",8,4),this._userInstancedBuffersStorage.vertexBuffers.world3=c.createVertexBuffer("world3",12,4),this._scene.needsPreviousWorldMatrices&&(h=new ri(r,o.instancesPreviousData,!0,16,!1,!0),o.instancesPreviousBuffer=h,this._userInstancedBuffersStorage.vertexBuffers.previousWorld0=h.createVertexBuffer("previousWorld0",0,4),this._userInstancedBuffersStorage.vertexBuffers.previousWorld1=h.createVertexBuffer("previousWorld1",4,4),this._userInstancedBuffersStorage.vertexBuffers.previousWorld2=h.createVertexBuffer("previousWorld2",8,4),this._userInstancedBuffersStorage.vertexBuffers.previousWorld3=h.createVertexBuffer("previousWorld3",12,4)),this._invalidateInstanceVertexArrayObject()):this._instanceDataStorage.isFrozen&&!this._instanceDataStorage.forceMatrixUpdates||(c.updateDirectly(o.instancesData,0,f),!this._scene.needsPreviousWorldMatrices||this._instanceDataStorage.manualUpdate&&!this._instanceDataStorage.previousManualUpdate||h.updateDirectly(o.instancesPreviousData,0,f)),this._processInstancedBuffers(s,_),this.getScene()._activeIndices.addCount(e.indexCount*f,!1),r._currentDrawContext&&(r._currentDrawContext.useInstancing=!0),this._bind(e,n,t),this._draw(e,t,f),!this._scene.needsPreviousWorldMatrices||m||!this._instanceDataStorage.manualUpdate||this._instanceDataStorage.isFrozen&&!this._instanceDataStorage.forceMatrixUpdates||this._instanceDataStorage.previousManualUpdate||h.updateDirectly(o.instancesData,0,f),r.unbindInstanceAttributes(),this}_renderWithThinInstances(e,t,i,n){const r=this._thinInstanceDataStorage?.instancesCount??0;this.getScene()._activeIndices.addCount(e.indexCount*r,!1),n._currentDrawContext&&(n._currentDrawContext.useInstancing=!0),this._bind(e,i,t),this._draw(e,t,r),this._scene.needsPreviousWorldMatrices&&!this._thinInstanceDataStorage.previousMatrixData&&this._thinInstanceDataStorage.matrixData&&(this._thinInstanceDataStorage.previousMatrixBuffer?this._thinInstanceDataStorage.previousMatrixBuffer.updateDirectly(this._thinInstanceDataStorage.matrixData,0,r):this._thinInstanceDataStorage.previousMatrixBuffer=this._thinInstanceCreateMatrixBuffer("previousWorld",this._thinInstanceDataStorage.matrixData,!1)),n.unbindInstanceAttributes()}_processInstancedBuffers(e,t){}_processRendering(e,t,i,n,r,s,a,o){const l=this.getScene(),c=l.getEngine();if(n=this._getRenderingFillMode(n),s&&t.getRenderingMesh().hasThinInstances)return this._renderWithThinInstances(t,n,i,c),this;if(s)this._renderWithInstances(t,n,r,i,c);else{c._currentDrawContext&&(c._currentDrawContext.useInstancing=!1);let i=0;r.renderSelf[t._id]&&(a&&a(!1,e.getWorldMatrix(),o),i++,this._draw(t,n,this._instanceDataStorage.overridenInstanceCount));const s=r.visibleInstances[t._id];if(s){const e=s.length;i+=e;for(let i=0;i<e;i++){const e=s[i].getWorldMatrix();a&&a(!0,e,o),this._draw(t,n)}}l._activeIndices.addCount(t.indexCount*i,!1)}return this}_rebuild(e=!1){if(this._instanceDataStorage.instancesBuffer&&(e&&this._instanceDataStorage.instancesBuffer.dispose(),this._instanceDataStorage.instancesBuffer=null),this._userInstancedBuffersStorage){for(const t in this._userInstancedBuffersStorage.vertexBuffers){const i=this._userInstancedBuffersStorage.vertexBuffers[t];i&&(e&&i.dispose(),this._userInstancedBuffersStorage.vertexBuffers[t]=null)}this._userInstancedBuffersStorage.vertexArrayObjects&&(this._userInstancedBuffersStorage.vertexArrayObjects={})}this._internalMeshDataInfo._effectiveMaterial=null,super._rebuild(e)}_freeze(){if(this.subMeshes){for(let e=0;e<this.subMeshes.length;e++)this._getInstancesRenderList(e);this._internalMeshDataInfo._effectiveMaterial=null,this._instanceDataStorage.isFrozen=!0}}_unFreeze(){this._instanceDataStorage.isFrozen=!1,this._instanceDataStorage.previousBatch=null}renderWithRenderPassId(e,t,i,n,r=!0){const s=this._scene.getEngine(),a=s.currentRenderPassId;if(void 0!==e&&(s.currentRenderPassId=e),n)(!r||r&&n.isInFrustum(this._scene._frustumPlanes))&&this.render(n,!!t,i);else for(let e=0;e<this.subMeshes.length;e++){const n=this.subMeshes[e];(!r||r&&n.isInFrustum(this._scene._frustumPlanes))&&this.render(n,!!t,i)}return void 0!==e&&(s.currentRenderPassId=a),this}render(e,t,i){const n=this.getScene();this._internalAbstractMeshDataInfo._isActiveIntermediate?this._internalAbstractMeshDataInfo._isActiveIntermediate=!1:this._internalAbstractMeshDataInfo._isActive=!1;const r=n.activeCameras?.length??0;if((r>1&&n.activeCamera===n.activeCameras[0]||r<=1)&&this._checkOcclusionQuery()&&!this._occlusionDataStorage.forceRenderingWhenOccluded)return this;const s=this._getInstancesRenderList(e._id,!!i);if(s.mustReturn)return this;if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;const a=n.getEngine();let o=0,l=null;this.ignoreCameraMaxZ&&n.activeCamera&&!n._isInIntermediateRendering()&&(o=n.activeCamera.maxZ,l=n.activeCamera,n.activeCamera.maxZ=0,n.updateTransformMatrix(!0)),this._internalMeshDataInfo._onBeforeRenderObservable&&this._internalMeshDataInfo._onBeforeRenderObservable.notifyObservers(this);const c=e.getRenderingMesh(),h=s.hardwareInstancedRendering[e._id]||c.hasThinInstances||!!this._userInstancedBuffersStorage&&!e.getMesh()._internalAbstractMeshDataInfo._actAsRegularMesh,d=this._instanceDataStorage,u=e.getMaterial();if(!u)return l&&(l.maxZ=o,n.updateTransformMatrix(!0)),this;if(d.isFrozen&&this._internalMeshDataInfo._effectiveMaterial&&this._internalMeshDataInfo._effectiveMaterial===u){if(u._storeEffectOnSubMeshes&&!e._drawWrapper?._wasPreviouslyReady||!u._storeEffectOnSubMeshes&&!u._getDrawWrapper()._wasPreviouslyReady)return l&&(l.maxZ=o,n.updateTransformMatrix(!0)),this}else{if(u._storeEffectOnSubMeshes){if(!u.isReadyForSubMesh(this,e,h))return l&&(l.maxZ=o,n.updateTransformMatrix(!0)),this}else if(!u.isReady(this,h))return l&&(l.maxZ=o,n.updateTransformMatrix(!0)),this;this._internalMeshDataInfo._effectiveMaterial=u}let f;t&&a.setAlphaMode(this._internalMeshDataInfo._effectiveMaterial.alphaMode),f=this._internalMeshDataInfo._effectiveMaterial._storeEffectOnSubMeshes?e._drawWrapper:this._internalMeshDataInfo._effectiveMaterial._getDrawWrapper();const _=f?.effect??null;for(const t of n._beforeRenderingMeshStage)t.action(this,e,s,_);if(!f||!_)return l&&(l.maxZ=o,n.updateTransformMatrix(!0)),this;const m=i||this;let p;if(d.isFrozen||!this._internalMeshDataInfo._effectiveMaterial.backFaceCulling&&null===this._internalMeshDataInfo._effectiveMaterial.sideOrientation&&!this._internalMeshDataInfo._effectiveMaterial.twoSidedLighting)p=d.sideOrientation;else{const e=m._getWorldMatrixDeterminant();p=this._internalMeshDataInfo._effectiveMaterial._getEffectiveOrientation(this),e<0&&(p=p===Ji.ClockWiseSideOrientation?Ji.CounterClockWiseSideOrientation:Ji.ClockWiseSideOrientation),d.sideOrientation=p}const g=this._internalMeshDataInfo._effectiveMaterial._preBind(f,p);this._internalMeshDataInfo._effectiveMaterial.forceDepthWrite&&a.setDepthWrite(!0);const E=this._internalMeshDataInfo._effectiveMaterial,T=E.fillMode;this._internalMeshDataInfo._onBeforeBindObservable&&this._internalMeshDataInfo._onBeforeBindObservable.notifyObservers(this),h||this._bind(e,_,T,!1);const A=m.getWorldMatrix();E._storeEffectOnSubMeshes?E.bindForSubMesh(A,this,e):E.bind(A,this),!E.backFaceCulling&&E.separateCullingPass&&(a.setState(!0,E.zOffset,!1,!g,E.cullBackFaces,E.stencil,E.zOffsetUnits),this._processRendering(this,e,_,T,s,h,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),a.setState(!0,E.zOffset,!1,g,E.cullBackFaces,E.stencil,E.zOffsetUnits),this._internalMeshDataInfo._onBetweenPassObservable&&this._internalMeshDataInfo._onBetweenPassObservable.notifyObservers(e)),this._processRendering(this,e,_,T,s,h,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),this._internalMeshDataInfo._effectiveMaterial.unbind();for(const t of n._afterRenderingMeshStage)t.action(this,e,s,_);return this._internalMeshDataInfo._onAfterRenderObservable&&this._internalMeshDataInfo._onAfterRenderObservable.notifyObservers(this),l&&(l.maxZ=o,n.updateTransformMatrix(!0)),2!==n.performancePriority||d.isFrozen||this._freeze(),this}cleanMatrixWeights(){this.isVerticesDataPresent(si.MatricesWeightsKind)&&(this.isVerticesDataPresent(si.MatricesWeightsExtraKind)?this._normalizeSkinWeightsAndExtra():this._normalizeSkinFourWeights())}_normalizeSkinFourWeights(){const e=this.getVerticesData(si.MatricesWeightsKind),t=e.length;for(let i=0;i<t;i+=4){const t=e[i]+e[i+1]+e[i+2]+e[i+3];if(0===t)e[i]=1;else{const n=1/t;e[i]*=n,e[i+1]*=n,e[i+2]*=n,e[i+3]*=n}}this.setVerticesData(si.MatricesWeightsKind,e)}_normalizeSkinWeightsAndExtra(){const e=this.getVerticesData(si.MatricesWeightsExtraKind),t=this.getVerticesData(si.MatricesWeightsKind),i=t.length;for(let n=0;n<i;n+=4){let i=t[n]+t[n+1]+t[n+2]+t[n+3];if(i+=e[n]+e[n+1]+e[n+2]+e[n+3],0===i)t[n]=1;else{const r=1/i;t[n]*=r,t[n+1]*=r,t[n+2]*=r,t[n+3]*=r,e[n]*=r,e[n+1]*=r,e[n+2]*=r,e[n+3]*=r}}this.setVerticesData(si.MatricesWeightsKind,t),this.setVerticesData(si.MatricesWeightsKind,e)}validateSkinning(){const e=this.getVerticesData(si.MatricesWeightsExtraKind),t=this.getVerticesData(si.MatricesWeightsKind);if(null===t||null==this.skeleton)return{skinned:!1,valid:!0,report:"not skinned"};const i=t.length;let n=0,r=0,s=0,a=0;const o=null===e?4:8,l=[];for(let e=0;e<=o;e++)l[e]=0;for(let c=0;c<i;c+=4){let i=t[c],h=i,d=0===h?0:1;for(let r=1;r<o;r++){const s=r<4?t[c+r]:e[c+r-4];s>i&&n++,0!==s&&d++,h+=s,i=s}if(l[d]++,d>s&&(s=d),0===h)r++;else{const i=1/h;let n=0;for(let r=0;r<o;r++)n+=r<4?Math.abs(t[c+r]-t[c+r]*i):Math.abs(e[c+r-4]-e[c+r-4]*i);n>.001&&a++}}const c=this.skeleton.bones.length,h=this.getVerticesData(si.MatricesIndicesKind),d=this.getVerticesData(si.MatricesIndicesExtraKind);let u=0;for(let e=0;e<i;e+=4)for(let t=0;t<o;t++){const i=t<4?h[e+t]:d[e+t-4];(i>=c||i<0)&&u++}return{skinned:!0,valid:0===r&&0===a&&0===u,report:"Number of Weights = "+i/4+"\nMaximum influences = "+s+"\nMissing Weights = "+r+"\nNot Sorted = "+n+"\nNot Normalized = "+a+"\nWeightCounts = ["+l+"]\nNumber of bones = "+c+"\nBad Bone Indices = "+u}}_checkDelayState(){const e=this.getScene();return this._geometry?this._geometry.load(e):this.delayLoadState===Ze.DELAYLOADSTATE_NOTLOADED&&(this.delayLoadState=Ze.DELAYLOADSTATE_LOADING,this._queueLoad(e)),this}_queueLoad(e){e.addPendingData(this);const t=-1!==this.delayLoadingFile.indexOf(".babylonbinarymeshdata");return Yt.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=Ze.DELAYLOADSTATE_LOADED,e.removePendingData(this)}),(()=>{}),e.offlineProvider,t),this}isInFrustum(e){return this.delayLoadState!==Ze.DELAYLOADSTATE_LOADING&&(!!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 n=this.getScene().multiMaterials;for(i=n.length-1;i>-1;i--)if(n[i].id===e)return this.material=n[i],this;return this}getAnimatables(){const e=[];return this.material&&e.push(this.material),this.skeleton&&e.push(this.skeleton),e}bakeTransformIntoVertices(e){if(!this.isVerticesDataPresent(si.PositionKind))return this;const t=this.subMeshes.splice(0);this._resetPointsArrayCache();let i=this.getVerticesData(si.PositionKind);const n=B.Zero();let r;for(r=0;r<i.length;r+=3)B.TransformCoordinatesFromFloatsToRef(i[r],i[r+1],i[r+2],e,n).toArray(i,r);if(this.setVerticesData(si.PositionKind,i,this.getVertexBuffer(si.PositionKind).isUpdatable()),this.isVerticesDataPresent(si.NormalKind)){for(i=this.getVerticesData(si.NormalKind),r=0;r<i.length;r+=3)B.TransformNormalFromFloatsToRef(i[r],i[r+1],i[r+2],e,n).normalize().toArray(i,r);this.setVerticesData(si.NormalKind,i,this.getVertexBuffer(si.NormalKind).isUpdatable())}if(this.isVerticesDataPresent(si.TangentKind)){for(i=this.getVerticesData(si.TangentKind),r=0;r<i.length;r+=4)B.TransformNormalFromFloatsToRef(i[r],i[r+1],i[r+2],e,n).normalize().toArray(i,r);this.setVerticesData(si.TangentKind,i,this.getVertexBuffer(si.TangentKind).isUpdatable())}return e.determinant()<0&&this.flipFaces(),this.releaseSubMeshes(),this.subMeshes=t,this}bakeCurrentTransformIntoVertices(e=!0){return this.bakeTransformIntoVertices(this.computeWorldMatrix(!0)),this.resetLocalMatrix(e),this}get _positions(){return this._internalAbstractMeshDataInfo._positions||this._geometry&&this._geometry._positions||null}_resetPointsArrayCache(){return this._geometry&&this._geometry._resetPointsArrayCache(),this}_generatePointsArray(){return!!this._geometry&&this._geometry._generatePointsArray()}clone(e="",t=null,i,n=!0){return new ln(e,this.getScene(),t,this,i,n)}dispose(e,t=!1){this.morphTargetManager=null,this._geometry&&this._geometry.releaseForMesh(this,!0);const i=this._internalMeshDataInfo;if(i._onBeforeDrawObservable&&i._onBeforeDrawObservable.clear(),i._onBeforeBindObservable&&i._onBeforeBindObservable.clear(),i._onBeforeRenderObservable&&i._onBeforeRenderObservable.clear(),i._onAfterRenderObservable&&i._onAfterRenderObservable.clear(),i._onBetweenPassObservable&&i._onBetweenPassObservable.clear(),this._scene.useClonedMeshMap){if(i.meshMap)for(const e in i.meshMap){const t=i.meshMap[e];t&&(t._internalMeshDataInfo._source=null,i.meshMap[e]=void 0)}i._source&&i._source._internalMeshDataInfo.meshMap&&(i._source._internalMeshDataInfo.meshMap[this.uniqueId]=void 0)}else{const e=this.getScene().meshes;for(const t of e){const e=t;e._internalMeshDataInfo&&e._internalMeshDataInfo._source&&e._internalMeshDataInfo._source===this&&(e._internalMeshDataInfo._source=null)}}i._source=null,this._instanceDataStorage.visibleInstances={},this._disposeInstanceSpecificData(),this._disposeThinInstanceSpecificData(),this._internalMeshDataInfo._checkReadinessObserver&&this._scene.onBeforeRenderObservable.remove(this._internalMeshDataInfo._checkReadinessObserver),super.dispose(e,t)}_disposeInstanceSpecificData(){}_disposeThinInstanceSpecificData(){}_invalidateInstanceVertexArrayObject(){}applyDisplacementMap(e,t,i,n,r,s,a=!1,o){const l=this.getScene();return Yt.LoadImage(e,(e=>{const o=e.width,l=e.height,c=this.getEngine().createCanvas(o,l).getContext("2d");c.drawImage(e,0,0);const h=c.getImageData(0,0,o,l).data;this.applyDisplacementMapFromBuffer(h,o,l,t,i,r,s,a),n&&n(this)}),o||(()=>{}),l.offlineProvider),this}applyDisplacementMapFromBuffer(e,t,i,n,r,s,a,o=!1){if(!this.isVerticesDataPresent(si.PositionKind)||!this.isVerticesDataPresent(si.NormalKind)||!this.isVerticesDataPresent(si.UVKind))return de.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing"),this;const l=this.getVerticesData(si.PositionKind,!0,!0),c=this.getVerticesData(si.NormalKind),h=this.getVerticesData(si.UVKind);let d=B.Zero();const u=B.Zero(),f=U.Zero();s=s||U.Zero(),a=a||new U(1,1);for(let o=0;o<l.length;o+=3){B.FromArrayToRef(l,o,d),B.FromArrayToRef(c,o,u),U.FromArrayToRef(h,o/3*2,f);const _=4*((Math.abs(f.x*a.x+s.x%1)*(t-1)%t|0)+(Math.abs(f.y*a.y+s.y%1)*(i-1)%i|0)*t),m=.3*(e[_]/255)+.59*(e[_+1]/255)+.11*(e[_+2]/255);u.normalize(),u.scaleInPlace(n+(r-n)*m),d=d.add(u),d.toArray(l,o)}return Ti.ComputeNormals(l,this.getIndices(),c),o?(this.setVerticesData(si.PositionKind,l),this.setVerticesData(si.NormalKind,c),this.setVerticesData(si.UVKind,h)):(this.updateVerticesData(si.PositionKind,l),this.updateVerticesData(si.NormalKind,c)),this}_getFlattenedNormals(e,t){const i=new Float32Array(3*e.length);let n=0;const r=this.sideOrientation===(this._scene.useRightHandedSystem?Ze.MATERIAL_CounterClockWiseSideOrientation:Ze.MATERIAL_ClockWiseSideOrientation);for(let s=0;s<e.length;s+=3){const a=B.FromArray(t,3*e[s]),o=B.FromArray(t,3*e[s+1]),l=B.FromArray(t,3*e[s+2]),c=a.subtract(o),h=l.subtract(o),d=B.Normalize(B.Cross(c,h));r&&d.scaleInPlace(-1);for(let e=0;e<3;e++)i[n++]=d.x,i[n++]=d.y,i[n++]=d.z}return i}_convertToUnIndexedMesh(e=!1){const t=this.getVerticesDataKinds().filter((e=>!this.getVertexBuffer(e)?.getIsInstanced())),i=this.getIndices(),n={},r=(e,t)=>{const n=new Float32Array(i.length*t);let r=0;for(let s=0;s<i.length;s++)for(let a=0;a<t;a++)n[r++]=e[i[s]*t+a];return n},s=this.getBoundingInfo(),a=this.geometry?this.subMeshes.slice(0):[];for(const e of t)n[e]=this.getVerticesData(e);for(const s of t){const t=this.getVertexBuffer(s),a=t.getSize();if(e&&s===si.NormalKind){const e=this._getFlattenedNormals(i,n[si.PositionKind]);this.setVerticesData(si.NormalKind,e,t.isUpdatable(),a)}else this.setVerticesData(s,r(n[s],a),t.isUpdatable(),a)}if(this.morphTargetManager){for(let t=0;t<this.morphTargetManager.numTargets;t++){const n=this.morphTargetManager.getTarget(t),s=n.getPositions();n.setPositions(r(s,3));const a=n.getNormals();a&&n.setNormals(e?this._getFlattenedNormals(i,s):r(a,3));const o=n.getTangents();o&&n.setTangents(r(o,3));const l=n.getUVs();l&&n.setUVs(r(l,2))}this.morphTargetManager.synchronize()}for(let e=0;e<i.length;e++)i[e]=e;this.setIndices(i),this._unIndexed=!0,this.releaseSubMeshes();for(const e of a){const t=e.getBoundingInfo();gi.AddToMesh(e.materialIndex,e.indexStart,e.indexCount,e.indexStart,e.indexCount,this).setBoundingInfo(t)}return this.setBoundingInfo(s),this.synchronizeInstances(),this}convertToFlatShadedMesh(){return this._convertToUnIndexedMesh(!0)}convertToUnIndexedMesh(){return this._convertToUnIndexedMesh()}flipFaces(e=!1){const t=Ti.ExtractFromMesh(this);let i;if(e&&this.isVerticesDataPresent(si.NormalKind)&&t.normals)for(i=0;i<t.normals.length;i++)t.normals[i]*=-1;if(t.indices){let e;for(i=0;i<t.indices.length;i+=3)e=t.indices[i+1],t.indices[i+1]=t.indices[i+2],t.indices[i+2]=e}return t.applyToMesh(this,this.isVertexBufferUpdatable(si.PositionKind)),this}increaseVertices(e=1){const t=Ti.ExtractFromMesh(this),i=t.indices&&!Array.isArray(t.indices)&&Array.from?Array.from(t.indices):t.indices,n=t.positions&&!Array.isArray(t.positions)&&Array.from?Array.from(t.positions):t.positions,r=t.uvs&&!Array.isArray(t.uvs)&&Array.from?Array.from(t.uvs):t.uvs,s=t.normals&&!Array.isArray(t.normals)&&Array.from?Array.from(t.normals):t.normals;if(i&&n){t.indices=i,t.positions=n,r&&(t.uvs=r),s&&(t.normals=s);const a=e+1,o=new Array;for(let e=0;e<a+1;e++)o[e]=new Array;let l,c;const h=new B(0,0,0),d=new B(0,0,0),u=new U(0,0),f=new Array,_=new Array,m=new Array;let p,g,E,T=n.length;r&&(g=r.length),s&&(E=s.length);for(let e=0;e<i.length;e+=3){_[0]=i[e],_[1]=i[e+1],_[2]=i[e+2];for(let e=0;e<3;e++)if(l=_[e],c=_[(e+1)%3],void 0===m[l]&&void 0===m[c]?(m[l]=new Array,m[c]=new Array):(void 0===m[l]&&(m[l]=new Array),void 0===m[c]&&(m[c]=new Array)),void 0===m[l][c]&&void 0===m[c][l]){m[l][c]=[],h.x=(n[3*c]-n[3*l])/a,h.y=(n[3*c+1]-n[3*l+1])/a,h.z=(n[3*c+2]-n[3*l+2])/a,s&&(d.x=(s[3*c]-s[3*l])/a,d.y=(s[3*c+1]-s[3*l+1])/a,d.z=(s[3*c+2]-s[3*l+2])/a),r&&(u.x=(r[2*c]-r[2*l])/a,u.y=(r[2*c+1]-r[2*l+1])/a),m[l][c].push(l);for(let e=1;e<a;e++)m[l][c].push(n.length/3),n[T++]=n[3*l]+e*h.x,n[T++]=n[3*l+1]+e*h.y,n[T++]=n[3*l+2]+e*h.z,s&&(s[E++]=s[3*l]+e*d.x,s[E++]=s[3*l+1]+e*d.y,s[E++]=s[3*l+2]+e*d.z),r&&(r[g++]=r[2*l]+e*u.x,r[g++]=r[2*l+1]+e*u.y);m[l][c].push(c),m[c][l]=new Array,p=m[l][c].length;for(let e=0;e<p;e++)m[c][l][e]=m[l][c][p-1-e]}o[0][0]=i[e],o[1][0]=m[i[e]][i[e+1]][1],o[1][1]=m[i[e]][i[e+2]][1];for(let t=2;t<a;t++){o[t][0]=m[i[e]][i[e+1]][t],o[t][t]=m[i[e]][i[e+2]][t],h.x=(n[3*o[t][t]]-n[3*o[t][0]])/t,h.y=(n[3*o[t][t]+1]-n[3*o[t][0]+1])/t,h.z=(n[3*o[t][t]+2]-n[3*o[t][0]+2])/t,s&&(d.x=(s[3*o[t][t]]-s[3*o[t][0]])/t,d.y=(s[3*o[t][t]+1]-s[3*o[t][0]+1])/t,d.z=(s[3*o[t][t]+2]-s[3*o[t][0]+2])/t),r&&(u.x=(r[2*o[t][t]]-r[2*o[t][0]])/t,u.y=(r[2*o[t][t]+1]-r[2*o[t][0]+1])/t);for(let e=1;e<t;e++)o[t][e]=n.length/3,n[T++]=n[3*o[t][0]]+e*h.x,n[T++]=n[3*o[t][0]+1]+e*h.y,n[T++]=n[3*o[t][0]+2]+e*h.z,s&&(s[E++]=s[3*o[t][0]]+e*d.x,s[E++]=s[3*o[t][0]+1]+e*d.y,s[E++]=s[3*o[t][0]+2]+e*d.z),r&&(r[g++]=r[2*o[t][0]]+e*u.x,r[g++]=r[2*o[t][0]+1]+e*u.y)}o[a]=m[i[e+1]][i[e+2]],f.push(o[0][0],o[1][0],o[1][1]);for(let e=1;e<a;e++){let t;for(t=0;t<e;t++)f.push(o[e][t],o[e+1][t],o[e+1][t+1]),f.push(o[e][t],o[e+1][t+1],o[e][t+1]);f.push(o[e][t],o[e+1][t],o[e+1][t+1])}}t.indices=f,t.applyToMesh(this,this.isVertexBufferUpdatable(si.PositionKind))}else de.Warn("Couldn't increase number of vertices : VertexData must contain at least indices and positions")}forceSharedVertices(){const e=Ti.ExtractFromMesh(this),t=e.uvs,i=e.indices,n=e.positions,r=e.colors,s=e.matricesIndices,a=e.matricesWeights,o=e.matricesIndicesExtra,l=e.matricesWeightsExtra;if(void 0===i||void 0===n||null===i||null===n)de.Warn("VertexData contains empty entries");else{const c=new Array,h=new Array,d=new Array,u=new Array,f=new Array,_=new Array,m=new Array,p=new Array;let g=new Array,E=0;const T={};let A,v;for(let e=0;e<i.length;e+=3){v=[i[e],i[e+1],i[e+2]],g=[];for(let e=0;e<3;e++){g[e]="";for(let t=0;t<3;t++)Math.abs(n[3*v[e]+t])<1e-8&&(n[3*v[e]+t]=0),g[e]+=n[3*v[e]+t]+"|"}if(g[0]!=g[1]&&g[0]!=g[2]&&g[1]!=g[2])for(let e=0;e<3;e++){if(A=T[g[e]],void 0===A){T[g[e]]=E,A=E++;for(let t=0;t<3;t++)c.push(n[3*v[e]+t]);if(null!=r)for(let t=0;t<4;t++)u.push(r[4*v[e]+t]);if(null!=t)for(let i=0;i<2;i++)d.push(t[2*v[e]+i]);if(null!=s)for(let t=0;t<4;t++)f.push(s[4*v[e]+t]);if(null!=a)for(let t=0;t<4;t++)_.push(a[4*v[e]+t]);if(null!=o)for(let t=0;t<4;t++)m.push(o[4*v[e]+t]);if(null!=l)for(let t=0;t<4;t++)p.push(l[4*v[e]+t])}h.push(A)}}const R=new Array;Ti.ComputeNormals(c,h,R),e.positions=c,e.indices=h,e.normals=R,null!=t&&(e.uvs=d),null!=r&&(e.colors=u),null!=s&&(e.matricesIndices=f),null!=a&&(e.matricesWeights=_),null!=o&&(e.matricesIndicesExtra=m),null!=a&&(e.matricesWeightsExtra=p),e.applyToMesh(this,this.isVertexBufferUpdatable(si.PositionKind))}}static _instancedMeshFactory(e,t){throw Y("InstancedMesh")}static _PhysicsImpostorParser(e,t,i){throw Y("PhysicsImpostor")}createInstance(e){return ln._instancedMeshFactory(e,this)}synchronizeInstances(){for(let e=0;e<this.instances.length;e++){this.instances[e]._syncSubMeshes()}return this}optimizeIndices(e){const t=this.getIndices(),i=this.getVerticesData(si.PositionKind);if(!i||!t)return this;const n=[];for(let e=0;e<i.length;e+=3)n.push(B.FromArray(i,e));const r=[];return Kt.SyncAsyncForLoop(n.length,40,(e=>{const t=n.length-1-e,i=n[t];for(let e=0;e<t;++e){const s=n[e];if(i.equals(s)){r[t]=e;break}}}),(()=>{for(let e=0;e<t.length;++e)t[e]=r[t[e]]||t[e];const i=this.subMeshes.slice(0);this.setIndices(t),this.subMeshes=i,e&&e(this)})),this}serialize(e={}){e.name=this.name,e.id=this.id,e.uniqueId=this.uniqueId,e.type=this.getClassName(),q&&q.HasTags(this)&&(e.tags=q.GetTags(this)),e.position=this.position.asArray(),this.rotationQuaternion?e.rotationQuaternion=this.rotationQuaternion.asArray():this.rotation&&(e.rotation=this.rotation.asArray()),e.scaling=this.scaling.asArray(),this._postMultiplyPivotMatrix?e.pivotMatrix=this.getPivotMatrix().asArray():e.localMatrix=this.getPivotMatrix().asArray(),e.isEnabled=this.isEnabled(!1),e.isVisible=this.isVisible,e.infiniteDistance=this.infiniteDistance,e.pickable=this.isPickable,e.receiveShadows=this.receiveShadows,e.billboardMode=this.billboardMode,e.visibility=this.visibility,e.alwaysSelectAsActiveMesh=this.alwaysSelectAsActiveMesh,e.checkCollisions=this.checkCollisions,e.ellipsoid=this.ellipsoid.asArray(),e.ellipsoidOffset=this.ellipsoidOffset.asArray(),e.doNotSyncBoundingInfo=this.doNotSyncBoundingInfo,e.isBlocker=this.isBlocker,e.sideOrientation=this.sideOrientation,this.parent&&this.parent._serializeAsParent(e),e.isUnIndexed=this.isUnIndexed;const t=this._geometry;if(t&&this.subMeshes){e.geometryUniqueId=t.uniqueId,e.geometryId=t.id,e.subMeshes=[];for(let t=0;t<this.subMeshes.length;t++){const i=this.subMeshes[t];e.subMeshes.push({materialIndex:i.materialIndex,verticesStart:i.verticesStart,verticesCount:i.verticesCount,indexStart:i.indexStart,indexCount:i.indexCount})}}if(this.material?this.material.doNotSerialize||(e.materialUniqueId=this.material.uniqueId,e.materialId=this.material.id):(this.material=null,e.materialUniqueId=this._scene.defaultMaterial.uniqueId,e.materialId=this._scene.defaultMaterial.id),this.morphTargetManager&&(e.morphTargetManagerId=this.morphTargetManager.uniqueId),this.skeleton&&(e.skeletonId=this.skeleton.id,e.numBoneInfluencers=this.numBoneInfluencers),this.getScene()._getComponent(en.NAME_PHYSICSENGINE)){const t=this.getPhysicsImpostor();t&&(e.physicsMass=t.getParam("mass"),e.physicsFriction=t.getParam("friction"),e.physicsRestitution=t.getParam("mass"),e.physicsImpostor=t.type)}this.metadata&&(e.metadata=this.metadata),e.instances=[];for(let t=0;t<this.instances.length;t++){const i=this.instances[t];if(i.doNotSerialize)continue;const n={name:i.name,id:i.id,isEnabled:i.isEnabled(!1),isVisible:i.isVisible,isPickable:i.isPickable,checkCollisions:i.checkCollisions,position:i.position.asArray(),scaling:i.scaling.asArray()};if(i.parent&&i.parent._serializeAsParent(n),i.rotationQuaternion?n.rotationQuaternion=i.rotationQuaternion.asArray():i.rotation&&(n.rotation=i.rotation.asArray()),this.getScene()._getComponent(en.NAME_PHYSICSENGINE)){const e=i.getPhysicsImpostor();e&&(n.physicsMass=e.getParam("mass"),n.physicsFriction=e.getParam("friction"),n.physicsRestitution=e.getParam("mass"),n.physicsImpostor=e.type)}i.metadata&&(n.metadata=i.metadata),i.actionManager&&(n.actions=i.actionManager.serialize(i.name)),e.instances.push(n),re.AppendSerializedAnimations(i,n),n.ranges=i.serializeAnimationRanges()}if(this._thinInstanceDataStorage.instancesCount&&this._thinInstanceDataStorage.matrixData&&(e.thinInstances={instancesCount:this._thinInstanceDataStorage.instancesCount,matrixData:Array.from(this._thinInstanceDataStorage.matrixData),matrixBufferSize:this._thinInstanceDataStorage.matrixBufferSize,enablePicking:this.thinInstanceEnablePicking},this._userThinInstanceBuffersStorage)){const t={data:{},sizes:{},strides:{}};for(const e in this._userThinInstanceBuffersStorage.data)t.data[e]=Array.from(this._userThinInstanceBuffersStorage.data[e]),t.sizes[e]=this._userThinInstanceBuffersStorage.sizes[e],t.strides[e]=this._userThinInstanceBuffersStorage.strides[e];e.thinInstances.userThinInstance=t}return re.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.layerMask=this.layerMask,e.alphaIndex=this.alphaIndex,e.hasVertexAlpha=this.hasVertexAlpha,e.overlayAlpha=this.overlayAlpha,e.overlayColor=this.overlayColor.asArray(),e.renderOverlay=this.renderOverlay,e.applyFog=this.applyFog,this.actionManager&&(e.actions=this.actionManager.serialize(this.name)),e}_syncGeometryWithMorphTargetManager(){if(!this.geometry)return;this._markSubMeshesAsAttributesDirty();const e=this._internalAbstractMeshDataInfo._morphTargetManager;if(e&&e.vertexCount){if(e.vertexCount!==this.getTotalVertices())return de.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count."),void(this.morphTargetManager=null);if(e.isUsingTextureForTargets)return;for(let t=0;t<e.numInfluencers;t++){const i=e.getActiveTarget(t),n=i.getPositions();if(!n)return void de.Error("Invalid morph target. Target must have positions.");this.geometry.setVerticesData(si.PositionKind+t,n,!1,3);const r=i.getNormals();r&&this.geometry.setVerticesData(si.NormalKind+t,r,!1,3);const s=i.getTangents();s&&this.geometry.setVerticesData(si.TangentKind+t,s,!1,3);const a=i.getUVs();a&&this.geometry.setVerticesData(si.UVKind+"_"+t,a,!1,2)}}else{let e=0;for(;this.geometry.isVerticesDataPresent(si.PositionKind+e);)this.geometry.removeVerticesData(si.PositionKind+e),this.geometry.isVerticesDataPresent(si.NormalKind+e)&&this.geometry.removeVerticesData(si.NormalKind+e),this.geometry.isVerticesDataPresent(si.TangentKind+e)&&this.geometry.removeVerticesData(si.TangentKind+e),this.geometry.isVerticesDataPresent(si.UVKind+e)&&this.geometry.removeVerticesData(si.UVKind+"_"+e),e++}}static Parse(e,t,i){let n;if(n=e.type&&"LinesMesh"===e.type?ln._LinesMeshParser(e,t):e.type&&"GroundMesh"===e.type?ln._GroundMeshParser(e,t):e.type&&"GoldbergMesh"===e.type?ln._GoldbergMeshParser(e,t):e.type&&"GreasedLineMesh"===e.type?ln._GreasedLineMeshParser(e,t):e.type&&"TrailMesh"===e.type?ln._TrailMeshParser(e,t):new ln(e.name,t),n.id=e.id,n._waitingParsedUniqueId=e.uniqueId,q&&q.AddTagsTo(n,e.tags),n.position=B.FromArray(e.position),void 0!==e.metadata&&(n.metadata=e.metadata),e.rotationQuaternion?n.rotationQuaternion=V.FromArray(e.rotationQuaternion):e.rotation&&(n.rotation=B.FromArray(e.rotation)),n.scaling=B.FromArray(e.scaling),e.localMatrix?n.setPreTransformMatrix(k.FromArray(e.localMatrix)):e.pivotMatrix&&n.setPivotMatrix(k.FromArray(e.pivotMatrix)),n.setEnabled(e.isEnabled),n.isVisible=e.isVisible,n.infiniteDistance=e.infiniteDistance,n.alwaysSelectAsActiveMesh=!!e.alwaysSelectAsActiveMesh,n.showBoundingBox=e.showBoundingBox,n.showSubMeshesBoundingBox=e.showSubMeshesBoundingBox,void 0!==e.applyFog&&(n.applyFog=e.applyFog),void 0!==e.pickable&&(n.isPickable=e.pickable),void 0!==e.alphaIndex&&(n.alphaIndex=e.alphaIndex),n.receiveShadows=e.receiveShadows,void 0!==e.billboardMode&&(n.billboardMode=e.billboardMode),void 0!==e.visibility&&(n.visibility=e.visibility),n.checkCollisions=e.checkCollisions,n.doNotSyncBoundingInfo=!!e.doNotSyncBoundingInfo,e.ellipsoid&&(n.ellipsoid=B.FromArray(e.ellipsoid)),e.ellipsoidOffset&&(n.ellipsoidOffset=B.FromArray(e.ellipsoidOffset)),null!=e.overrideMaterialSideOrientation&&(n.sideOrientation=e.overrideMaterialSideOrientation),void 0!==e.sideOrientation&&(n.sideOrientation=e.sideOrientation),void 0!==e.isBlocker&&(n.isBlocker=e.isBlocker),n._shouldGenerateFlatShading=e.useFlatShading,e.freezeWorldMatrix&&(n._waitingData.freezeWorldMatrix=e.freezeWorldMatrix),void 0!==e.parentId&&(n._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(n._waitingParentInstanceIndex=e.parentInstanceIndex),void 0!==e.actions&&(n._waitingData.actions=e.actions),void 0!==e.overlayAlpha&&(n.overlayAlpha=e.overlayAlpha),void 0!==e.overlayColor&&(n.overlayColor=ee.FromArray(e.overlayColor)),void 0!==e.renderOverlay&&(n.renderOverlay=e.renderOverlay),n.isUnIndexed=!!e.isUnIndexed,n.hasVertexAlpha=e.hasVertexAlpha,e.delayLoadingFile?(n.delayLoadState=Ze.DELAYLOADSTATE_NOTLOADED,n.delayLoadingFile=i+e.delayLoadingFile,n.buildBoundingInfo(B.FromArray(e.boundingBoxMinimum),B.FromArray(e.boundingBoxMaximum)),e._binaryInfo&&(n._binaryInfo=e._binaryInfo),n._delayInfo=[],e.hasUVs&&n._delayInfo.push(si.UVKind),e.hasUVs2&&n._delayInfo.push(si.UV2Kind),e.hasUVs3&&n._delayInfo.push(si.UV3Kind),e.hasUVs4&&n._delayInfo.push(si.UV4Kind),e.hasUVs5&&n._delayInfo.push(si.UV5Kind),e.hasUVs6&&n._delayInfo.push(si.UV6Kind),e.hasColors&&n._delayInfo.push(si.ColorKind),e.hasMatricesIndices&&n._delayInfo.push(si.MatricesIndicesKind),e.hasMatricesWeights&&n._delayInfo.push(si.MatricesWeightsKind),n._delayLoadingFunction=vi._ImportGeometry,Ai.ForceFullSceneLoadingForIncremental&&n._checkDelayState()):vi._ImportGeometry(e,n),e.materialUniqueId?n._waitingMaterialId=e.materialUniqueId:e.materialId&&(n._waitingMaterialId=e.materialId),e.morphTargetManagerId>-1&&(n.morphTargetManager=t.getMorphTargetManagerById(e.morphTargetManagerId)),void 0!==e.skeletonId&&null!==e.skeletonId&&(n.skeleton=t.getLastSkeletonById(e.skeletonId),e.numBoneInfluencers&&(n.numBoneInfluencers=e.numBoneInfluencers)),e.animations){for(let t=0;t<e.animations.length;t++){const i=e.animations[t],r=x("BABYLON.Animation");r&&n.animations.push(r.Parse(i))}ae.ParseAnimationRanges(n,e,t)}if(e.autoAnimate&&t.beginAnimation(n,e.autoAnimateFrom,e.autoAnimateTo,e.autoAnimateLoop,e.autoAnimateSpeed||1),e.layerMask&&!isNaN(e.layerMask)?n.layerMask=Math.abs(parseInt(e.layerMask)):n.layerMask=268435455,e.physicsImpostor&&(n.physicsImpostor=ln._PhysicsImpostorParser(t,n,e)),e.lodMeshIds&&(n._waitingData.lods={ids:e.lodMeshIds,distances:e.lodDistances?e.lodDistances:null,coverages:e.lodCoverages?e.lodCoverages:null}),e.instances)for(let i=0;i<e.instances.length;i++){const r=e.instances[i],s=n.createInstance(r.name);if(r.id&&(s.id=r.id),q&&(r.tags?q.AddTagsTo(s,r.tags):q.AddTagsTo(s,e.tags)),s.position=B.FromArray(r.position),void 0!==r.metadata&&(s.metadata=r.metadata),void 0!==r.parentId&&(s._waitingParentId=r.parentId),void 0!==r.parentInstanceIndex&&(s._waitingParentInstanceIndex=r.parentInstanceIndex),void 0!==r.isEnabled&&null!==r.isEnabled&&s.setEnabled(r.isEnabled),void 0!==r.isVisible&&null!==r.isVisible&&(s.isVisible=r.isVisible),void 0!==r.isPickable&&null!==r.isPickable&&(s.isPickable=r.isPickable),r.rotationQuaternion?s.rotationQuaternion=V.FromArray(r.rotationQuaternion):r.rotation&&(s.rotation=B.FromArray(r.rotation)),s.scaling=B.FromArray(r.scaling),null!=r.checkCollisions&&null!=r.checkCollisions&&(s.checkCollisions=r.checkCollisions),null!=r.pickable&&null!=r.pickable&&(s.isPickable=r.pickable),null!=r.showBoundingBox&&null!=r.showBoundingBox&&(s.showBoundingBox=r.showBoundingBox),null!=r.showSubMeshesBoundingBox&&null!=r.showSubMeshesBoundingBox&&(s.showSubMeshesBoundingBox=r.showSubMeshesBoundingBox),null!=r.alphaIndex&&null!=r.showSubMeshesBoundingBox&&(s.alphaIndex=r.alphaIndex),r.physicsImpostor&&(s.physicsImpostor=ln._PhysicsImpostorParser(t,s,r)),void 0!==r.actions&&(s._waitingData.actions=r.actions),r.animations){for(let e=0;e<r.animations.length;e++){const t=r.animations[e],i=x("BABYLON.Animation");i&&s.animations.push(i.Parse(t))}ae.ParseAnimationRanges(s,r,t),r.autoAnimate&&t.beginAnimation(s,r.autoAnimateFrom,r.autoAnimateTo,r.autoAnimateLoop,r.autoAnimateSpeed||1)}}if(e.thinInstances){const t=e.thinInstances;if(n.thinInstanceEnablePicking=!!t.enablePicking,t.matrixData?(n.thinInstanceSetBuffer("matrix",new Float32Array(t.matrixData),16,!1),n._thinInstanceDataStorage.matrixBufferSize=t.matrixBufferSize,n._thinInstanceDataStorage.instancesCount=t.instancesCount):n._thinInstanceDataStorage.matrixBufferSize=t.matrixBufferSize,e.thinInstances.userThinInstance){const t=e.thinInstances.userThinInstance;for(const e in t.data)n.thinInstanceSetBuffer(e,new Float32Array(t.data[e]),t.strides[e],!1),n._userThinInstanceBuffersStorage.sizes[e]=t.sizes[e]}}return n}setPositionsForCPUSkinning(){const e=this._internalMeshDataInfo;if(!e._sourcePositions){const t=this.getVerticesData(si.PositionKind);if(!t)return e._sourcePositions;e._sourcePositions=new Float32Array(t),this.isVertexBufferUpdatable(si.PositionKind)||this.setVerticesData(si.PositionKind,t,!0)}return e._sourcePositions}setNormalsForCPUSkinning(){const e=this._internalMeshDataInfo;if(!e._sourceNormals){const t=this.getVerticesData(si.NormalKind);if(!t)return e._sourceNormals;e._sourceNormals=new Float32Array(t),this.isVertexBufferUpdatable(si.NormalKind)||this.setVerticesData(si.NormalKind,t,!0)}return e._sourceNormals}applySkeleton(e){if(!this.geometry)return this;if(this.geometry._softwareSkinningFrameId==this.getScene().getFrameId())return this;if(this.geometry._softwareSkinningFrameId=this.getScene().getFrameId(),!this.isVerticesDataPresent(si.PositionKind))return this;if(!this.isVerticesDataPresent(si.MatricesIndicesKind))return this;if(!this.isVerticesDataPresent(si.MatricesWeightsKind))return this;const t=this.isVerticesDataPresent(si.NormalKind),i=this._internalMeshDataInfo;if(!i._sourcePositions){const e=this.subMeshes.slice();this.setPositionsForCPUSkinning(),this.subMeshes=e}t&&!i._sourceNormals&&this.setNormalsForCPUSkinning();let n=this.getVerticesData(si.PositionKind);if(!n)return this;n instanceof Float32Array||(n=new Float32Array(n));let r=this.getVerticesData(si.NormalKind);if(t){if(!r)return this;r instanceof Float32Array||(r=new Float32Array(r))}const s=this.getVerticesData(si.MatricesIndicesKind),a=this.getVerticesData(si.MatricesWeightsKind);if(!a||!s)return this;const o=this.numBoneInfluencers>4,l=o?this.getVerticesData(si.MatricesIndicesExtraKind):null,c=o?this.getVerticesData(si.MatricesWeightsExtraKind):null,h=e.getTransformMatrices(this),d=B.Zero(),u=new k,f=new k;let _,m=0;for(let e=0;e<n.length;e+=3,m+=4){let p;for(_=0;_<4;_++)p=a[m+_],p>0&&(k.FromFloat32ArrayToRefScaled(h,Math.floor(16*s[m+_]),p,f),u.addToSelf(f));if(o)for(_=0;_<4;_++)p=c[m+_],p>0&&(k.FromFloat32ArrayToRefScaled(h,Math.floor(16*l[m+_]),p,f),u.addToSelf(f));B.TransformCoordinatesFromFloatsToRef(i._sourcePositions[e],i._sourcePositions[e+1],i._sourcePositions[e+2],u,d),d.toArray(n,e),t&&(B.TransformNormalFromFloatsToRef(i._sourceNormals[e],i._sourceNormals[e+1],i._sourceNormals[e+2],u,d),d.toArray(r,e)),u.reset()}return this.updateVerticesData(si.PositionKind,n),t&&this.updateVerticesData(si.NormalKind,r),this}static MinMax(e){let t=null,i=null;return e.forEach((function(e){const n=e.getBoundingInfo().boundingBox;t&&i?(t.minimizeInPlace(n.minimumWorld),i.maximizeInPlace(n.maximumWorld)):(t=n.minimumWorld,i=n.maximumWorld)})),t&&i?{min:t,max:i}:{min:B.Zero(),max:B.Zero()}}static Center(e){const t=e instanceof Array?ln.MinMax(e):e;return B.Center(t.min,t.max)}static MergeMeshes(e,t=!0,i,n,r,s){return Qt(ln._MergeMeshesCoroutine(e,t,i,n,r,s,!1))}static MergeMeshesAsync(e,t=!0,i,n,r,s){return a=ln._MergeMeshesCoroutine(e,t,i,n,r,s,!0),o=function(e=25){let t;return(i,n,r)=>{const s=performance.now();void 0===t||s-t>e?(t=s,setTimeout((()=>{qt(i,n,r)}),0)):qt(i,n,r)}}(),new Promise(((e,t)=>{jt(a,o,e,t)}));var a,o}static*_MergeMeshesCoroutine(e,t=!0,i,n,r,s,a){if(0===(e=e.filter(Boolean)).length)return null;let o;if(!i){let t=0;for(o=0;o<e.length;o++)if(t+=e[o].getTotalVertices(),t>=65536)return de.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices"),null}s&&(r=!1);const l=new Array,c=new Array,h=new Array,d=e[0].sideOrientation;for(o=0;o<e.length;o++){const t=e[o];if(t.isAnInstance)return de.Warn("Cannot merge instance meshes."),null;if(d!==t.sideOrientation)return de.Warn("Cannot merge meshes with different sideOrientation values."),null;if(r&&h.push(t.getTotalIndices()),s)if(t.material){const e=t.material;if(e instanceof $i){for(let t=0;t<e.subMaterials.length;t++)l.indexOf(e.subMaterials[t])<0&&l.push(e.subMaterials[t]);for(let i=0;i<t.subMeshes.length;i++)c.push(l.indexOf(e.subMaterials[t.subMeshes[i].materialIndex])),h.push(t.subMeshes[i].indexCount)}else{l.indexOf(e)<0&&l.push(e);for(let i=0;i<t.subMeshes.length;i++)c.push(l.indexOf(e)),h.push(t.subMeshes[i].indexCount)}}else for(let e=0;e<t.subMeshes.length;e++)c.push(0),h.push(t.subMeshes[e].indexCount)}const u=e[0],f=e=>{const t=e.computeWorldMatrix(!0);return{vertexData:Ti.ExtractFromMesh(e,!1,!1),transform:t}},{vertexData:_,transform:m}=f(u);a&&(yield);const p=new Array(e.length-1);for(let t=1;t<e.length;t++)p[t-1]=f(e[t]),a&&(yield);const g=_._mergeCoroutine(m,p,i,a,!t);let E=g.next();for(;!E.done;)a&&(yield),E=g.next();const T=E.value;n||(n=new ln(u.name+"_merged",u.getScene()));const A=T._applyToCoroutine(n,void 0,a);let v=A.next();for(;!v.done;)a&&(yield),v=A.next();if(n.checkCollisions=u.checkCollisions,n.sideOrientation=u.sideOrientation,t)for(o=0;o<e.length;o++)e[o].dispose();if(r||s){n.releaseSubMeshes(),o=0;let e=0;for(;o<h.length;)gi.CreateFromIndices(0,e,h[o],n,void 0,!1),e+=h[o],o++;for(const e of n.subMeshes)e.refreshBoundingInfo();n.computeWorldMatrix(!0)}if(s){const e=new $i(u.name+"_merged",u.getScene());e.subMaterials=l;for(let e=0;e<n.subMeshes.length;e++)n.subMeshes[e].materialIndex=c[e];n.material=e}else n.material=u.material;return n}addInstance(e){e._indexInSourceMeshInstanceArray=this.instances.length,this.instances.push(e)}removeInstance(e){const t=e._indexInSourceMeshInstanceArray;if(-1!=t){if(t!==this.instances.length-1){const e=this.instances[this.instances.length-1];this.instances[t]=e,e._indexInSourceMeshInstanceArray=t}e._indexInSourceMeshInstanceArray=-1,this.instances.pop()}}_shouldConvertRHS(){return this._scene.useRightHandedSystem&&this.sideOrientation===Ji.CounterClockWiseSideOrientation}_getRenderingFillMode(e){const t=this.getScene();return t.forcePointsCloud?Ji.PointFillMode:t.forceWireframe?Ji.WireFrameFillMode:this.overrideRenderingFillMode??e}setMaterialByID(e){return this.setMaterialById(e)}static CreateRibbon(e,t,i,n,r,s,a,o,l){throw new Error("Import MeshBuilder to populate this function")}static CreateDisc(e,t,i,n,r,s){throw new Error("Import MeshBuilder to populate this function")}static CreateBox(e,t,i,n,r){throw new Error("Import MeshBuilder to populate this function")}static CreateSphere(e,t,i,n,r,s){throw new Error("Import MeshBuilder to populate this function")}static CreateHemisphere(e,t,i,n){throw new Error("Import MeshBuilder to populate this function")}static CreateCylinder(e,t,i,n,r,s,a,o,l){throw new Error("Import MeshBuilder to populate this function")}static CreateTorus(e,t,i,n,r,s,a){throw new Error("Import MeshBuilder to populate this function")}static CreateTorusKnot(e,t,i,n,r,s,a,o,l,c){throw new Error("Import MeshBuilder to populate this function")}static CreateLines(e,t,i,n,r){throw new Error("Import MeshBuilder to populate this function")}static CreateDashedLines(e,t,i,n,r,s,a,o){throw new Error("Import MeshBuilder to populate this function")}static CreatePolygon(e,t,i,n,r,s,a){throw new Error("Import MeshBuilder to populate this function")}static ExtrudePolygon(e,t,i,n,r,s,a,o){throw new Error("Import MeshBuilder to populate this function")}static ExtrudeShape(e,t,i,n,r,s,a,o,l,c){throw new Error("Import MeshBuilder to populate this function")}static ExtrudeShapeCustom(e,t,i,n,r,s,a,o,l,c,h,d){throw new Error("Import MeshBuilder to populate this function")}static CreateLathe(e,t,i,n,r,s,a){throw new Error("Import MeshBuilder to populate this function")}static CreatePlane(e,t,i,n,r){throw new Error("Import MeshBuilder to populate this function")}static CreateGround(e,t,i,n,r,s){throw new Error("Import MeshBuilder to populate this function")}static CreateTiledGround(e,t,i,n,r,s,a,o,l){throw new Error("Import MeshBuilder to populate this function")}static CreateGroundFromHeightMap(e,t,i,n,r,s,a,o,l,c,h){throw new Error("Import MeshBuilder to populate this function")}static CreateTube(e,t,i,n,r,s,a,o,l,c){throw new Error("Import MeshBuilder to populate this function")}static CreatePolyhedron(e,t,i){throw new Error("Import MeshBuilder to populate this function")}static CreateIcoSphere(e,t,i){throw new Error("Import MeshBuilder to populate this function")}static CreateDecal(e,t,i,n,r,s){throw new Error("Import MeshBuilder to populate this function")}static CreateCapsule(e,t,i){throw new Error("Import MeshBuilder to populate this function")}static ExtendToGoldberg(e){throw new Error("Import MeshBuilder to populate this function")}}ln.FRONTSIDE=Ti.FRONTSIDE,ln.BACKSIDE=Ti.BACKSIDE,ln.DOUBLESIDE=Ti.DOUBLESIDE,ln.DEFAULTSIDE=Ti.DEFAULTSIDE,ln.NO_CAP=0,ln.CAP_START=1,ln.CAP_END=2,ln.CAP_ALL=3,ln.NO_FLIP=0,ln.FLIP_TILE=1,ln.ROTATE_TILE=2,ln.FLIP_ROW=3,ln.ROTATE_ROW=4,ln.FLIP_N_ROTATE_TILE=5,ln.FLIP_N_ROTATE_ROW=6,ln.CENTER=0,ln.LEFT=1,ln.RIGHT=2,ln.TOP=3,ln.BOTTOM=4,ln.INSTANCEDMESH_SORT_TRANSPARENT=!1,ln._GroundMeshParser=(e,t)=>{throw Y("GroundMesh")},ln._GoldbergMeshParser=(e,t)=>{throw Y("GoldbergMesh")},ln._LinesMeshParser=(e,t)=>{throw Y("LinesMesh")},ln._GreasedLineMeshParser=(e,t)=>{throw Y("GreasedLineMesh")},ln._GreasedLineRibbonMeshParser=(e,t)=>{throw Y("GreasedLineRibbonMesh")},ln._TrailMeshParser=(e,t)=>{throw Y("TrailMesh")},M("BABYLON.Mesh",ln);class cn{}cn.POINTERDOWN=1,cn.POINTERUP=2,cn.POINTERMOVE=4,cn.POINTERWHEEL=8,cn.POINTERPICK=16,cn.POINTERTAP=32,cn.POINTERDOUBLETAP=64;class hn{constructor(e,t){this.type=e,this.event=t}}class dn extends hn{constructor(e,t,i,n){super(e,t),this.ray=null,this.originalPickingInfo=null,this.skipOnPointerObservable=!1,this.localPosition=new U(i,n)}}class un extends hn{get pickInfo(){return this._pickInfo||this._generatePickInfo(),this._pickInfo}constructor(e,t,i,n=null){super(e,t),this._pickInfo=i,this._inputManager=n}_generatePickInfo(){this._inputManager&&(this._pickInfo=this._inputManager._pickMove(this.event),this._inputManager._setRayOnPointerInfo(this._pickInfo,this.event),this._inputManager=null)}}class fn{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!==cn.POINTERDOWN?e.type===cn.POINTERUP&&(this._isPointerDown=!1):this._isPointerDown=!0})),this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add((()=>{if(this._reachTargetAlpha())return;const e=_e.Now;let t=0;null!=this._lastFrameTime&&(t=e-this._lastFrameTime),this._lastFrameTime=e,this._applyUserInteraction();const i=e-this._lastInteractionTime-this._idleRotationWaitTime,n=Math.max(Math.min(i/this._idleRotationSpinupTime,1),0);this._cameraRotationSpeed=this._idleRotationSpeed*n,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}resetLastInteractionTime(e){this._lastInteractionTime=e??_e.Now}_reachTargetAlpha(){return!(!this._attachedCamera||!this.targetAlpha)&&Math.abs(this._attachedCamera.alpha-this.targetAlpha)<A}_userIsZooming(){return!!this._attachedCamera&&0!==this._attachedCamera.inertialRadiusOffset}_shouldAnimationStopForInteraction(){if(!this._attachedCamera)return!1;let e=!1;return this._lastFrameRadius===this._attachedCamera.radius&&0!==this._attachedCamera.inertialRadiusOffset&&(e=!0),this._lastFrameRadius=this._attachedCamera.radius,this._zoomStopsAnimation?e:this._userIsZooming()}_applyUserInteraction(){this._userIsMoving()&&!this._shouldAnimationStopForInteraction()&&(this._lastInteractionTime=_e.Now)}_userIsMoving(){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)}}var _n;!function(e){e[e.CW=0]="CW",e[e.CCW=1]="CCW"}(_n||(_n={}));class mn{constructor(){this._easingMode=mn.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 mn.EASINGMODE_EASEIN:return this.easeInCore(e);case mn.EASINGMODE_EASEOUT:return 1-this.easeInCore(1-e)}return e>=.5?.5*(1-this.easeInCore(2*(1-e)))+.5:.5*this.easeInCore(2*e)}}mn.EASINGMODE_EASEIN=0,mn.EASINGMODE_EASEOUT=1,mn.EASINGMODE_EASEINOUT=2;class pn{constructor(e,t,i){this.name=e,this.from=t,this.to=i}clone(){return new pn(this.name,this.from,this.to)}}class gn{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 gn(this.width*e,this.height*t)}clone(){return new gn(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 gn(0,0)}add(e){return new gn(this.width+e.width,this.height+e.height)}subtract(e){return new gn(this.width-e.width,this.height-e.height)}scale(e){return new gn(this.width*e,this.height*e)}static Lerp(e,t,i){const n=e.width+(t.width-e.width)*i,r=e.height+(t.height-e.height)*i;return new gn(n,r)}}const En=Object.freeze(new V(0,0,0,0)),Tn=Object.freeze(B.Zero()),An=Object.freeze(U.Zero()),vn=Object.freeze(gn.Zero()),Rn=Object.freeze(ee.Black()),Sn=Object.freeze(new te(0,0,0,0)),In={key:0,repeatCount:0,loopMode:2};class Cn{static _PrepareAnimation(e,t,i,n,r,s,a,o){let l;if(!isNaN(parseFloat(r))&&isFinite(r)?l=Cn.ANIMATIONTYPE_FLOAT:r instanceof V?l=Cn.ANIMATIONTYPE_QUATERNION:r instanceof B?l=Cn.ANIMATIONTYPE_VECTOR3:r instanceof U?l=Cn.ANIMATIONTYPE_VECTOR2:r instanceof ee?l=Cn.ANIMATIONTYPE_COLOR3:r instanceof te?l=Cn.ANIMATIONTYPE_COLOR4:r instanceof gn&&(l=Cn.ANIMATIONTYPE_SIZE),null==l)return null;const c=new Cn(e,t,i,l,a),h=[{frame:0,value:r},{frame:n,value:s}];return c.setKeys(h),void 0!==o&&c.setEasingFunction(o),c}static CreateAnimation(e,t,i,n){const r=new Cn(e+"Animation",e,i,t,Cn.ANIMATIONLOOPMODE_CONSTANT);return r.setEasingFunction(n),r}static CreateAndStartAnimation(e,t,i,n,r,s,a,o,l,c,h){const d=Cn._PrepareAnimation(e,i,n,r,s,a,o,l);return d?(t.getScene&&(h=t.getScene()),h?h.beginDirectAnimation(t,[d],0,r,1===d.loopMode,1,c):null):null}static CreateAndStartHierarchyAnimation(e,t,i,n,r,s,a,o,l,c,h){const d=Cn._PrepareAnimation(e,n,r,s,a,o,l,c);if(!d)return null;return t.getScene().beginDirectHierarchyAnimation(t,i,[d],0,s,1===d.loopMode,1,h)}static CreateMergeAndStartAnimation(e,t,i,n,r,s,a,o,l,c){const h=Cn._PrepareAnimation(e,i,n,r,s,a,o,l);return h?(t.animations.push(h),t.getScene().beginAnimation(t,0,r,1===h.loopMode,1,c)):null}static MakeAnimationAdditive(e,t,i,n=!1,r){let s;s="object"==typeof t?t:{referenceFrame:t??0,range:i,cloneOriginalAnimation:n,clonedAnimationName:r};let a=e;if(s.cloneOriginalAnimation&&(a=e.clone(),a.name=s.clonedAnimationName||a.name),!a._keys.length)return a;const o=s.referenceFrame&&s.referenceFrame>=0?s.referenceFrame:0;let l=0;const c=a._keys[0];let h=a._keys.length-1;const d=a._keys[h],u={referenceValue:c.value,referencePosition:H.Vector3[0],referenceQuaternion:H.Quaternion[0],referenceScaling:H.Vector3[1],keyPosition:H.Vector3[2],keyQuaternion:H.Quaternion[1],keyScaling:H.Vector3[3]};let f=c.frame,_=d.frame;if(s.range){const e=a.getRange(s.range);e&&(f=e.from,_=e.to)}else f=s.fromFrame??f,_=s.toFrame??_;if(f!==c.frame&&(l=a.createKeyForFrame(f)),_!==d.frame&&(h=a.createKeyForFrame(_)),1===a._keys.length){const e=a._getKeyValue(a._keys[0]);u.referenceValue=e.clone?e.clone():e}else if(o<=c.frame){const e=a._getKeyValue(c.value);u.referenceValue=e.clone?e.clone():e}else if(o>=d.frame){const e=a._getKeyValue(d.value);u.referenceValue=e.clone?e.clone():e}else{In.key=0;const e=a._interpolate(o,In);u.referenceValue=e.clone?e.clone():e}a.dataType===Cn.ANIMATIONTYPE_QUATERNION?u.referenceValue.normalize().conjugateInPlace():a.dataType===Cn.ANIMATIONTYPE_MATRIX&&(u.referenceValue.decompose(u.referenceScaling,u.referenceQuaternion,u.referencePosition),u.referenceQuaternion.normalize().conjugateInPlace());let m=Number.MAX_VALUE;const p=s.clipKeys?[]:null;for(let e=l;e<=h;e++){let t=a._keys[e];if((p||s.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},p&&(m===Number.MAX_VALUE&&(m=t.frame),t.frame-=m,p.push(t))),!e||a.dataType===Cn.ANIMATIONTYPE_FLOAT||t.value!==c.value)switch(a.dataType){case Cn.ANIMATIONTYPE_MATRIX:t.value.decompose(u.keyScaling,u.keyQuaternion,u.keyPosition),u.keyPosition.subtractInPlace(u.referencePosition),u.keyScaling.divideInPlace(u.referenceScaling),u.referenceQuaternion.multiplyToRef(u.keyQuaternion,u.keyQuaternion),k.ComposeToRef(u.keyScaling,u.keyQuaternion,u.keyPosition,t.value);break;case Cn.ANIMATIONTYPE_QUATERNION:u.referenceValue.multiplyToRef(t.value,t.value);break;case Cn.ANIMATIONTYPE_VECTOR2:case Cn.ANIMATIONTYPE_VECTOR3:case Cn.ANIMATIONTYPE_COLOR3:case Cn.ANIMATIONTYPE_COLOR4:t.value.subtractToRef(u.referenceValue,t.value);break;case Cn.ANIMATIONTYPE_SIZE:t.value.width-=u.referenceValue.width,t.value.height-=u.referenceValue.height;break;default:t.value-=u.referenceValue}}return p&&a.setKeys(p,!0),a}static TransitionTo(e,t,i,n,r,s,a,o=null){if(a<=0)return i[e]=t,o&&o(),null;const l=r*(a/1e3);s.setKeys([{frame:0,value:i[e].clone?i[e].clone():i[e]},{frame:l,value:t}]),i.animations||(i.animations=[]),i.animations.push(s);const c=n.beginAnimation(i,0,l,!1);return c.onAnimationEnd=o,c}get runtimeAnimations(){return this._runtimeAnimations}get hasRunningRuntimeAnimations(){for(const e of this._runtimeAnimations)if(!e.isStopped())return!0;return!1}constructor(e,t,i,n,r,s){this.name=e,this.targetProperty=t,this.framePerSecond=i,this.dataType=n,this.loopMode=r,this.enableBlending=s,this._easingFunction=null,this._runtimeAnimations=new Array,this._events=new Array,this.blendingSpeed=.01,this._ranges={},this.targetPropertyPath=t.split("."),this.dataType=n,this.loopMode=void 0===r?Cn.ANIMATIONLOOPMODE_CYCLE:r,this.uniqueId=Cn._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<this._events.length;t++)this._events[t].frame===e&&(this._events.splice(t,1),t--)}getEvents(){return this._events}createRange(e,t,i){this._ranges[e]||(this._ranges[e]=new pn(e,t,i))}deleteRange(e,t=!0){const i=this._ranges[e];if(i){if(t){const e=i.from,t=i.to;for(let i=this._keys.length-1;i>=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;t<i;t++)e<this._keys[t].frame&&(e=this._keys[t].frame);return e}getEasingFunction(){return this._easingFunction}setEasingFunction(e){this._easingFunction=e}floatInterpolateFunction(e,t,i){return j.Lerp(e,t,i)}floatInterpolateFunctionWithTangents(e,t,i,n,r){return j.Hermite(e,t,i,n,r)}quaternionInterpolateFunction(e,t,i){return V.Slerp(e,t,i)}quaternionInterpolateFunctionWithTangents(e,t,i,n,r){return V.Hermite(e,t,i,n,r).normalize()}vector3InterpolateFunction(e,t,i){return B.Lerp(e,t,i)}vector3InterpolateFunctionWithTangents(e,t,i,n,r){return B.Hermite(e,t,i,n,r)}vector2InterpolateFunction(e,t,i){return U.Lerp(e,t,i)}vector2InterpolateFunctionWithTangents(e,t,i,n,r){return U.Hermite(e,t,i,n,r)}sizeInterpolateFunction(e,t,i){return gn.Lerp(e,t,i)}color3InterpolateFunction(e,t,i){return ee.Lerp(e,t,i)}color3InterpolateFunctionWithTangents(e,t,i,n,r){return ee.Hermite(e,t,i,n,r)}color4InterpolateFunction(e,t,i){return te.Lerp(e,t,i)}color4InterpolateFunctionWithTangents(e,t,i,n,r){return te.Hermite(e,t,i,n,r)}_getKeyValue(e){return"function"==typeof e?e():e}evaluate(e){return In.key=0,this._interpolate(e,In)}_interpolate(e,t,i=!1){if(t.loopMode===Cn.ANIMATIONLOOPMODE_CONSTANT&&t.repeatCount>0)return t.highLimitValue.clone?t.highLimitValue.clone():t.highLimitValue;const n=this._keys,r=n.length;let s=t.key;for(;s>=0&&e<n[s].frame;)--s;for(;s+1<=r-1&&e>=n[s+1].frame;)++s;if(t.key=s,s<0)return i?void 0:this._getKeyValue(n[0].value);if(s+1>r-1)return i?void 0:this._getKeyValue(n[r-1].value);const a=n[s],o=n[s+1];if(i&&(e===a.frame||e===o.frame))return;const l=this._getKeyValue(a.value),c=this._getKeyValue(o.value);if(1===a.interpolation)return o.frame>e?l:c;const h=void 0!==a.outTangent&&void 0!==o.inTangent,d=o.frame-a.frame;let u=(e-a.frame)/d;const f=a.easingFunction||this.getEasingFunction();switch(null!==f&&(u=f.ease(u)),this.dataType){case Cn.ANIMATIONTYPE_FLOAT:{const e=h?this.floatInterpolateFunctionWithTangents(l,a.outTangent*d,c,o.inTangent*d,u):this.floatInterpolateFunction(l,c,u);switch(t.loopMode){case Cn.ANIMATIONLOOPMODE_CYCLE:case Cn.ANIMATIONLOOPMODE_CONSTANT:case Cn.ANIMATIONLOOPMODE_YOYO:return e;case Cn.ANIMATIONLOOPMODE_RELATIVE:case Cn.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return(t.offsetValue??0)*t.repeatCount+e}break}case Cn.ANIMATIONTYPE_QUATERNION:{const e=h?this.quaternionInterpolateFunctionWithTangents(l,a.outTangent.scale(d),c,o.inTangent.scale(d),u):this.quaternionInterpolateFunction(l,c,u);switch(t.loopMode){case Cn.ANIMATIONLOOPMODE_CYCLE:case Cn.ANIMATIONLOOPMODE_CONSTANT:case Cn.ANIMATIONLOOPMODE_YOYO:return e;case Cn.ANIMATIONLOOPMODE_RELATIVE:case Cn.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.addInPlace((t.offsetValue||En).scale(t.repeatCount))}return e}case Cn.ANIMATIONTYPE_VECTOR3:{const e=h?this.vector3InterpolateFunctionWithTangents(l,a.outTangent.scale(d),c,o.inTangent.scale(d),u):this.vector3InterpolateFunction(l,c,u);switch(t.loopMode){case Cn.ANIMATIONLOOPMODE_CYCLE:case Cn.ANIMATIONLOOPMODE_CONSTANT:case Cn.ANIMATIONLOOPMODE_YOYO:return e;case Cn.ANIMATIONLOOPMODE_RELATIVE:case Cn.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.add((t.offsetValue||Tn).scale(t.repeatCount))}break}case Cn.ANIMATIONTYPE_VECTOR2:{const e=h?this.vector2InterpolateFunctionWithTangents(l,a.outTangent.scale(d),c,o.inTangent.scale(d),u):this.vector2InterpolateFunction(l,c,u);switch(t.loopMode){case Cn.ANIMATIONLOOPMODE_CYCLE:case Cn.ANIMATIONLOOPMODE_CONSTANT:case Cn.ANIMATIONLOOPMODE_YOYO:return e;case Cn.ANIMATIONLOOPMODE_RELATIVE:case Cn.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.add((t.offsetValue||An).scale(t.repeatCount))}break}case Cn.ANIMATIONTYPE_SIZE:switch(t.loopMode){case Cn.ANIMATIONLOOPMODE_CYCLE:case Cn.ANIMATIONLOOPMODE_CONSTANT:case Cn.ANIMATIONLOOPMODE_YOYO:return this.sizeInterpolateFunction(l,c,u);case Cn.ANIMATIONLOOPMODE_RELATIVE:case Cn.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return this.sizeInterpolateFunction(l,c,u).add((t.offsetValue||vn).scale(t.repeatCount))}break;case Cn.ANIMATIONTYPE_COLOR3:{const e=h?this.color3InterpolateFunctionWithTangents(l,a.outTangent.scale(d),c,o.inTangent.scale(d),u):this.color3InterpolateFunction(l,c,u);switch(t.loopMode){case Cn.ANIMATIONLOOPMODE_CYCLE:case Cn.ANIMATIONLOOPMODE_CONSTANT:case Cn.ANIMATIONLOOPMODE_YOYO:return e;case Cn.ANIMATIONLOOPMODE_RELATIVE:case Cn.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.add((t.offsetValue||Rn).scale(t.repeatCount))}break}case Cn.ANIMATIONTYPE_COLOR4:{const e=h?this.color4InterpolateFunctionWithTangents(l,a.outTangent.scale(d),c,o.inTangent.scale(d),u):this.color4InterpolateFunction(l,c,u);switch(t.loopMode){case Cn.ANIMATIONLOOPMODE_CYCLE:case Cn.ANIMATIONLOOPMODE_CONSTANT:case Cn.ANIMATIONLOOPMODE_YOYO:return e;case Cn.ANIMATIONLOOPMODE_RELATIVE:case Cn.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.add((t.offsetValue||Sn).scale(t.repeatCount))}break}case Cn.ANIMATIONTYPE_MATRIX:switch(t.loopMode){case Cn.ANIMATIONLOOPMODE_CYCLE:case Cn.ANIMATIONLOOPMODE_CONSTANT:case Cn.ANIMATIONLOOPMODE_YOYO:return Cn.AllowMatricesInterpolation?this.matrixInterpolateFunction(l,c,u,t.workValue):l;case Cn.ANIMATIONLOOPMODE_RELATIVE:case Cn.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return l}}return 0}matrixInterpolateFunction(e,t,i,n){return Cn.AllowMatrixDecomposeForInterpolation?n?(k.DecomposeLerpToRef(e,t,i,n),n):k.DecomposeLerp(e,t,i):n?(k.LerpToRef(e,t,i,n),n):k.Lerp(e,t,i)}clone(){const e=new Cn(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){In.key=0;const t=this._interpolate(e,In,!0);if(!t)return this._keys[In.key].frame===e?In.key:In.key+1;const i={frame:e,value:t.clone?t.clone():t};return this._keys.splice(In.key+1,0,i),In.key+1}serialize(){const e={};e.name=this.name,e.property=this.targetProperty,e.framePerSecond=this.framePerSecond,e.dataType=this.dataType,e.loopBehavior=this.loopMode,e.enableBlending=this.enableBlending,e.blendingSpeed=this.blendingSpeed;const t=this.dataType;e.keys=[];const i=this.getKeys();for(let n=0;n<i.length;n++){const r=i[n],s={};switch(s.frame=r.frame,t){case Cn.ANIMATIONTYPE_FLOAT:s.values=[r.value],void 0!==r.inTangent&&s.values.push(r.inTangent),void 0!==r.outTangent&&(void 0===r.inTangent&&s.values.push(void 0),s.values.push(r.outTangent)),void 0!==r.interpolation&&(void 0===r.inTangent&&s.values.push(void 0),void 0===r.outTangent&&s.values.push(void 0),s.values.push(r.interpolation));break;case Cn.ANIMATIONTYPE_QUATERNION:case Cn.ANIMATIONTYPE_MATRIX:case Cn.ANIMATIONTYPE_VECTOR3:case Cn.ANIMATIONTYPE_COLOR3:case Cn.ANIMATIONTYPE_COLOR4:s.values=r.value.asArray(),null!=r.inTangent&&s.values.push(r.inTangent.asArray()),null!=r.outTangent&&(void 0===r.inTangent&&s.values.push(void 0),s.values.push(r.outTangent.asArray())),void 0!==r.interpolation&&(void 0===r.inTangent&&s.values.push(void 0),void 0===r.outTangent&&s.values.push(void 0),s.values.push(r.interpolation))}e.keys.push(s)}e.ranges=[];for(const t in this._ranges){const i=this._ranges[t];if(!i)continue;const n={};n.name=t,n.from=i.from,n.to=i.to,e.ranges.push(n)}return e}static _UniversalLerp(e,t,i){const n=e.constructor;return n.Lerp?n.Lerp(e,t,i):n.Slerp?n.Slerp(e,t,i):e.toFixed?e*(1-i)+i*t:t}static Parse(e){const t=new Cn(e.name,e.property,e.framePerSecond,e.dataType,e.loopBehavior),i=e.dataType,n=[];let r,s;for(e.enableBlending&&(t.enableBlending=e.enableBlending),e.blendingSpeed&&(t.blendingSpeed=e.blendingSpeed),s=0;s<e.keys.length;s++){const t=e.keys[s];let a,o,l;switch(i){case Cn.ANIMATIONTYPE_FLOAT:r=t.values[0],t.values.length>=2&&(a=t.values[1]),t.values.length>=3&&(o=t.values[2]),t.values.length>=4&&(l=t.values[3]);break;case Cn.ANIMATIONTYPE_QUATERNION:if(r=V.FromArray(t.values),t.values.length>=8){const e=V.FromArray(t.values.slice(4,8));e.equals(V.Zero())||(a=e)}if(t.values.length>=12){const e=V.FromArray(t.values.slice(8,12));e.equals(V.Zero())||(o=e)}t.values.length>=13&&(l=t.values[12]);break;case Cn.ANIMATIONTYPE_MATRIX:r=k.FromArray(t.values),t.values.length>=17&&(l=t.values[16]);break;case Cn.ANIMATIONTYPE_COLOR3:r=ee.FromArray(t.values),t.values[3]&&(a=ee.FromArray(t.values[3])),t.values[4]&&(o=ee.FromArray(t.values[4])),t.values[5]&&(l=t.values[5]);break;case Cn.ANIMATIONTYPE_COLOR4:r=te.FromArray(t.values),t.values[4]&&(a=te.FromArray(t.values[4])),t.values[5]&&(o=te.FromArray(t.values[5])),t.values[6]&&(l=te.FromArray(t.values[6]));break;case Cn.ANIMATIONTYPE_VECTOR3:default:r=B.FromArray(t.values),t.values[3]&&(a=B.FromArray(t.values[3])),t.values[4]&&(o=B.FromArray(t.values[4])),t.values[5]&&(l=t.values[5])}const c={};c.frame=t.frame,c.value=r,null!=a&&(c.inTangent=a),null!=o&&(c.outTangent=o),null!=l&&(c.interpolation=l),n.push(c)}if(t.setKeys(n),e.ranges)for(s=0;s<e.ranges.length;s++)r=e.ranges[s],t.createRange(r.name,r.from,r.to);return t}static AppendSerializedAnimations(e,t){re.AppendSerializedAnimations(e,t)}static ParseFromFileAsync(e,t){return new Promise(((i,n)=>{const r=new me;r.addEventListener("readystatechange",(()=>{if(4==r.readyState)if(200==r.status){let t=JSON.parse(r.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 n=this.Parse(t);e&&(n.name=e),i(n)}}else n("Unable to load the animation")})),r.open("GET",t),r.send()}))}static ParseFromSnippetAsync(e){return new Promise(((t,i)=>{const n=new me;n.addEventListener("readystatechange",(()=>{if(4==n.readyState)if(200==n.status){const i=JSON.parse(JSON.parse(n.responseText).jsonPayload);if(i.animations){const n=JSON.parse(i.animations),r=[];for(const t of n.animations){const i=this.Parse(t);i.snippetId=e,r.push(i)}t(r)}else{const n=JSON.parse(i.animation),r=this.Parse(n);r.snippetId=e,t(r)}}else i("Unable to load the snippet "+e)})),n.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),n.send()}))}}Cn._UniqueIdGenerator=0,Cn.AllowMatricesInterpolation=!1,Cn.AllowMatrixDecomposeForInterpolation=!0,Cn.SnippetUrl=Ze.SnippetUrl,Cn.ANIMATIONTYPE_FLOAT=0,Cn.ANIMATIONTYPE_VECTOR3=1,Cn.ANIMATIONTYPE_QUATERNION=2,Cn.ANIMATIONTYPE_MATRIX=3,Cn.ANIMATIONTYPE_COLOR3=4,Cn.ANIMATIONTYPE_COLOR4=7,Cn.ANIMATIONTYPE_VECTOR2=5,Cn.ANIMATIONTYPE_SIZE=6,Cn.ANIMATIONLOOPMODE_RELATIVE=0,Cn.ANIMATIONLOOPMODE_CYCLE=1,Cn.ANIMATIONLOOPMODE_CONSTANT=2,Cn.ANIMATIONLOOPMODE_YOYO=4,Cn.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT=5,Cn.CreateFromSnippetAsync=Cn.ParseFromSnippetAsync,M("BABYLON.Animation",Cn),ae._AnimationRangeFactory=(e,t,i)=>new pn(e,t,i);class Mn{constructor(){this.transitionDuration=450,this.lowerRadiusTransitionRange=2,this.upperRadiusTransitionRange=-2,this._autoTransitionRange=!1,this._radiusIsAnimating=!1,this._radiusBounceTransition=null,this._animatables=new Array}get name(){return"Bouncing"}get autoTransitionRange(){return this._autoTransitionRange}set autoTransitionRange(e){if(this._autoTransitionRange===e)return;this._autoTransitionRange=e;const t=this._attachedCamera;t&&(e?this._onMeshTargetChangedObserver=t.onMeshTargetChangedObservable.add((e=>{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||(Mn.EasingFunction.setEasingMode(Mn.EasingMode),this._radiusBounceTransition=Cn.CreateAnimation("radius",Cn.ANIMATIONTYPE_FLOAT,60,Mn.EasingFunction)),this._cachedWheelPrecision=this._attachedCamera.wheelPrecision,this._attachedCamera.wheelPrecision=1/0,this._attachedCamera.inertialRadiusOffset=0,this.stopAllAnimations(),this._radiusIsAnimating=!0;const t=Cn.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()}}Mn.EasingFunction=new class extends mn{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)}}(.3),Mn.EasingMode=mn.EASINGMODE_EASEOUT;class xn{constructor(){this.onTargetFramingAnimationEndObservable=new g,this._mode=xn.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();xn.EasingFunction.setEasingMode(xn.EasingMode),this._onPrePointerObservableObserver=t.onPrePointerObservable.add((e=>{e.type!==cn.POINTERDOWN?e.type===cn.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 n=e.getBoundingInfo().boundingBox;this.zoomOnBoundingInfo(n.minimumWorld,n.maximumWorld,t,i)}zoomOnMeshHierarchy(e,t=!1,i=null){e.computeWorldMatrix(!0);const n=e.getHierarchyBoundingVectors(!0);this.zoomOnBoundingInfo(n.min,n.max,t,i)}zoomOnMeshesHierarchy(e,t=!1,i=null){const n=new B(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),r=new B(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);for(let t=0;t<e.length;t++){const i=e[t].getHierarchyBoundingVectors(!0);B.CheckExtends(i.min,n,r),B.CheckExtends(i.max,n,r)}this.zoomOnBoundingInfo(n,r,t,i)}zoomOnBoundingInfo(e,t,i=!1,n=null){let r;if(!this._attachedCamera)return!1;const s=e.y,a=s+(t.y-s)*this._positionScale,o=t.subtract(e).scale(.5);if(i)r=new B(0,a,0);else{const t=e.add(o);r=new B(t.x,a,t.z)}this._vectorTransition||(this._vectorTransition=Cn.CreateAnimation("target",Cn.ANIMATIONTYPE_VECTOR3,60,xn.EasingFunction)),this._betaIsAnimating=!0;let l=Cn.TransitionTo("target",r,this._attachedCamera,this._attachedCamera.getScene(),60,this._vectorTransition,this._framingTime);l&&this._animatables.push(l);let c=0;if(this._mode===xn.FitFrustumSidesMode){const i=this._calculateLowerRadiusFromModelBoundingSphere(e,t);this.autoCorrectCameraLimitsAndSensibility&&(this._attachedCamera.lowerRadiusLimit=o.length()+this._attachedCamera.minZ),c=i}else this._mode===xn.IgnoreBoundsSizeMode&&(c=this._calculateLowerRadiusFromModelBoundingSphere(e,t),this.autoCorrectCameraLimitsAndSensibility&&null===this._attachedCamera.lowerRadiusLimit&&(this._attachedCamera.lowerRadiusLimit=this._attachedCamera.minZ));if(this.autoCorrectCameraLimitsAndSensibility){const i=t.subtract(e).length();this._attachedCamera.panningSensibility=5e3/i,this._attachedCamera.wheelPrecision=100/c}return this._radiusTransition||(this._radiusTransition=Cn.CreateAnimation("radius",Cn.ANIMATIONTYPE_FLOAT,60,xn.EasingFunction)),l=Cn.TransitionTo("radius",c,this._attachedCamera,this._attachedCamera.getScene(),60,this._radiusTransition,this._framingTime,(()=>{this.stopAllAnimations(),n&&n(),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 n=i._calculateLowerRadiusFromModelBoundingSphere(e,t,this._radiusScale);return i.lowerRadiusLimit&&this._mode===xn.IgnoreBoundsSizeMode&&(n=n<i.lowerRadiusLimit?i.lowerRadiusLimit:n),i.upperRadiusLimit&&(n=n>i.upperRadiusLimit?i.upperRadiusLimit:n),n}_maintainCameraAboveGround(){if(this._elevationReturnTime<0)return;const e=_e.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=Cn.CreateAnimation("beta",Cn.ANIMATIONTYPE_FLOAT,60,xn.EasingFunction));const e=Cn.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=_e.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)}}xn.EasingFunction=new class extends mn{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)}},xn.EasingMode=mn.EASINGMODE_EASEINOUT,xn.IgnoreBoundsSizeMode=0,xn.FitFrustumSidesMode=1,ae.AddNodeConstructor("TargetCamera",((e,t)=>()=>new bn(e,B.Zero(),t)));class bn extends ii{constructor(e,t,i,n=!0){super(e,t,i,n),this._tmpUpVector=B.Zero(),this._tmpTargetVector=B.Zero(),this.cameraDirection=new B(0,0,0),this.cameraRotation=new U(0,0),this.ignoreParentScaling=!1,this.updateUpVectorFromRotation=!1,this._tmpQuaternion=new V,this.rotation=new B(0,0,0),this.speed=2,this.noRotationConstraint=!1,this.invertRotation=!1,this.inverseRotationSpeed=.2,this.lockedTarget=null,this._currentTarget=B.Zero(),this._initialFocalDistance=1,this._viewMatrix=k.Zero(),this._camMatrix=k.Zero(),this._cameraTransformMatrix=k.Zero(),this._cameraRotationMatrix=k.Zero(),this._referencePoint=new B(0,0,1),this._transformedReferencePoint=B.Zero(),this._deferredPositionUpdate=new B,this._deferredRotationQuaternionUpdate=new V,this._deferredRotationUpdate=new B,this._deferredUpdated=!1,this._deferOnly=!1,this._defaultUp=B.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 B(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotation=new B(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotationQuaternion=new V(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+=A),this._referencePoint.normalize().scaleInPlace(this._initialFocalDistance),k.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&&V.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(H.Matrix[0]),B.TransformNormalToRef(this.cameraDirection,H.Matrix[0],H.Vector3[0]),this._deferredPositionUpdate.addInPlace(H.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)}if(this._deferOnly?this._deferredUpdated=!0:this.rotation.copyFrom(this._deferredRotationUpdate),this.rotationQuaternion){this._deferredRotationUpdate.lengthSquared()&&(V.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.speed*A&&(this.cameraDirection.x=0),Math.abs(this.cameraDirection.y)<this.speed*A&&(this.cameraDirection.y=0),Math.abs(this.cameraDirection.z)<this.speed*A&&(this.cameraDirection.z=0),this.cameraDirection.scaleInPlace(this.inertia)),i&&(Math.abs(this.cameraRotation.x)<this.speed*A&&(this.cameraRotation.x=0),Math.abs(this.cameraRotation.y)<this.speed*A&&(this.cameraRotation.y=0),this.cameraRotation.scaleInPlace(this.inertia)),super._checkInputs()}_updateCameraRotationMatrix(){this.rotationQuaternion?this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix):k.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,this._cameraRotationMatrix)}_rotateUpVectorWithCameraRotationMatrix(){return B.TransformNormalToRef(this._defaultUp,this._cameraRotationMatrix,this.upVector),this}_getViewMatrix(){return this.lockedTarget&&this.setTarget(this._getLockedTargetPosition()),this._updateCameraRotationMatrix(),this.rotationQuaternion&&this._cachedQuaternionRotationZ!=this.rotationQuaternion.z?(this._rotateUpVectorWithCameraRotationMatrix(),this._cachedQuaternionRotationZ=this.rotationQuaternion.z):this._cachedRotationZ!==this.rotation.z&&(this._rotateUpVectorWithCameraRotationMatrix(),this._cachedRotationZ=this.rotation.z),B.TransformCoordinatesToRef(this._referencePoint,this._cameraRotationMatrix,this._transformedReferencePoint),this.position.addToRef(this._transformedReferencePoint,this._currentTarget),this.updateUpVectorFromRotation&&(this.rotationQuaternion?Ui.Y.rotateByQuaternionToRef(this.rotationQuaternion,this.upVector):(V.FromEulerVectorToRef(this.rotation,this._tmpQuaternion),Ui.Y.rotateByQuaternionToRef(this._tmpQuaternion,this.upVector))),this._computeViewMatrix(this.position,this._currentTarget,this.upVector),this._viewMatrix}_computeViewMatrix(e,t,i){if(this.ignoreParentScaling){if(this.parent){const n=this.parent.getWorldMatrix();B.TransformCoordinatesToRef(e,n,this._globalPosition),B.TransformCoordinatesToRef(t,n,this._tmpTargetVector),B.TransformNormalToRef(i,n,this._tmpUpVector),this._markSyncedWithParent()}else this._globalPosition.copyFrom(e),this._tmpTargetVector.copyFrom(t),this._tmpUpVector.copyFrom(i);this.getScene().useRightHandedSystem?k.LookAtRHToRef(this._globalPosition,this._tmpTargetVector,this._tmpUpVector,this._viewMatrix):k.LookAtLHToRef(this._globalPosition,this._tmpTargetVector,this._tmpUpVector,this._viewMatrix)}else if(this.getScene().useRightHandedSystem?k.LookAtRHToRef(e,t,i,this._viewMatrix):k.LookAtLHToRef(e,t,i,this._viewMatrix),this.parent){const e=this.parent.getWorldMatrix();this._viewMatrix.invert(),this._viewMatrix.multiplyToRef(e,this._viewMatrix),this._viewMatrix.getTranslationToRef(this._globalPosition),this._viewMatrix.invert(),this._markSyncedWithParent()}else this._globalPosition.copyFrom(e)}createRigCamera(e,t){if(this.cameraRigMode!==ii.RIG_MODE_NONE){const t=new bn(e,this.position.clone(),this.getScene());return t.isRigCamera=!0,t.rigParent=this,this.cameraRigMode===ii.RIG_MODE_VR&&(this.rotationQuaternion||(this.rotationQuaternion=new V),t._cameraRigParams={},t.rotationQuaternion=new V),t.mode=this.mode,t.orthoLeft=this.orthoLeft,t.orthoRight=this.orthoRight,t.orthoTop=this.orthoTop,t.orthoBottom=this.orthoBottom,t}return null}_updateRigCameras(){const e=this._rigCameras[0],t=this._rigCameras[1];switch(this.computeWorldMatrix(),this.cameraRigMode){case ii.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case ii.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case ii.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:case ii.RIG_MODE_STEREOSCOPIC_OVERUNDER:case ii.RIG_MODE_STEREOSCOPIC_INTERLACED:{const i=this.cameraRigMode===ii.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED?1:-1,n=this.cameraRigMode===ii.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED?-1:1;this._getRigCamPositionAndTarget(this._cameraRigParams.stereoHalfAngle*i,e),this._getRigCamPositionAndTarget(this._cameraRigParams.stereoHalfAngle*n,t);break}case ii.RIG_MODE_VR:e.rotationQuaternion?(e.rotationQuaternion.copyFrom(this.rotationQuaternion),t.rotationQuaternion.copyFrom(this.rotationQuaternion)):(e.rotation.copyFrom(this.rotation),t.rotation.copyFrom(this.rotation)),e.position.copyFrom(this.position),t.position.copyFrom(this.position)}super._updateRigCameras()}_getRigCamPositionAndTarget(e,t){this.getTarget().subtractToRef(this.position,bn._TargetFocalPoint),bn._TargetFocalPoint.normalize().scaleInPlace(this._initialFocalDistance);const i=bn._TargetFocalPoint.addInPlace(this.position);k.TranslationToRef(-i.x,-i.y,-i.z,bn._TargetTransformMatrix),bn._TargetTransformMatrix.multiplyToRef(k.RotationAxis(t.upVector,e),bn._RigCamTransformMatrix),k.TranslationToRef(i.x,i.y,i.z,bn._TargetTransformMatrix),bn._RigCamTransformMatrix.multiplyToRef(bn._TargetTransformMatrix,bn._RigCamTransformMatrix),B.TransformCoordinatesToRef(this.position,bn._RigCamTransformMatrix,t.position),t.setTarget(i)}getClassName(){return"TargetCamera"}}bn._RigCamTransformMatrix=new k,bn._TargetTransformMatrix=new k,bn._TargetFocalPoint=new B,e([h()],bn.prototype,"rotation",void 0),e([a()],bn.prototype,"speed",void 0),e([d("lockedTargetId")],bn.prototype,"lockedTarget",void 0);var yn,On={};class Dn{constructor(e){this.attachedToElement=!1,this.attached={},this.camera=e,this.checkInputs=()=>{}}add(e){const t=e.getSimpleName();this.attached[t]?de.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=!ii.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],n=re.Serialize(i);t[i.getClassName()]=n}e.inputsmgr=t}parse(e){const t=e.inputsmgr;if(t){this.clear();for(const e in t){const i=On[e];if(i){const n=t[e],r=re.Parse((()=>new i),n,null);this.add(r)}}}else for(const t in this.attached){const i=On[this.attached[t].getClassName()];if(i){const n=re.Parse((()=>new i),e,null);this.remove(this.attached[t]),this.add(n)}}}}class Nn{constructor(){this._currentActiveButton=-1,this.buttons=[0,1,2]}attachControl(e){e=Yt.BackCompatCameraNoPreventDefault(arguments);const t=this.camera.getEngine(),i=t.getInputElement();let n=0,r=null;this._pointA=null,this._pointB=null,this._altKey=!1,this._ctrlKey=!1,this._metaKey=!1,this._shiftKey=!1,this._buttonsPressed=0,this._pointerInput=s=>{const a=s.event,o="touch"===a.pointerType;if(s.type!==cn.POINTERMOVE&&-1===this.buttons.indexOf(a.button))return;const l=a.target;if(this._altKey=a.altKey,this._ctrlKey=a.ctrlKey,this._metaKey=a.metaKey,this._shiftKey=a.shiftKey,this._buttonsPressed=a.buttons,t.isPointerLock){const e=a.movementX,t=a.movementY;this.onTouch(null,e,t),this._pointA=null,this._pointB=null}else{if(s.type!==cn.POINTERDOWN&&s.type!==cn.POINTERDOUBLETAP&&o&&this._pointA?.pointerId!==a.pointerId&&this._pointB?.pointerId!==a.pointerId)return;if(s.type!==cn.POINTERDOWN||-1!==this._currentActiveButton&&!o)if(s.type===cn.POINTERDOUBLETAP)this.onDoubleTap(a.pointerType);else if(s.type!==cn.POINTERUP||this._currentActiveButton!==a.button&&!o){if(s.type===cn.POINTERMOVE)if(e||a.preventDefault(),this._pointA&&null===this._pointB){const e=a.clientX-this._pointA.x,t=a.clientY-this._pointA.y;this._pointA.x=a.clientX,this._pointA.y=a.clientY,this.onTouch(this._pointA,e,t)}else if(this._pointA&&this._pointB){const e=this._pointA.pointerId===a.pointerId?this._pointA:this._pointB;e.x=a.clientX,e.y=a.clientY;const t=this._pointA.x-this._pointB.x,i=this._pointA.y-this._pointB.y,o=t*t+i*i,l={x:(this._pointA.x+this._pointB.x)/2,y:(this._pointA.y+this._pointB.y)/2,pointerId:a.pointerId,type:s.type};this.onMultiTouch(this._pointA,this._pointB,n,o,r,l),r=l,n=o}}else{try{l?.releasePointerCapture(a.pointerId)}catch(e){}o||(this._pointB=null),t._badOS?this._pointA=this._pointB=null:this._pointB&&this._pointA&&this._pointA.pointerId==a.pointerId?(this._pointA=this._pointB,this._pointB=null):this._pointA&&this._pointB&&this._pointB.pointerId==a.pointerId?this._pointB=null:this._pointA=this._pointB=null,(0!==n||r)&&(this.onMultiTouch(this._pointA,this._pointB,n,0,r,null),n=0,r=null),this._currentActiveButton=-1,this.onButtonUp(a),e||a.preventDefault()}else{try{l?.setPointerCapture(a.pointerId)}catch(e){}if(null===this._pointA)this._pointA={x:a.clientX,y:a.clientY,pointerId:a.pointerId,type:a.pointerType};else{if(null!==this._pointB)return;this._pointB={x:a.clientX,y:a.clientY,pointerId:a.pointerId,type:a.pointerType}}-1!==this._currentActiveButton||o||(this._currentActiveButton=a.button),this.onButtonDown(a),e||(a.preventDefault(),i&&i.focus())}}},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,cn.POINTERDOWN|cn.POINTERUP|cn.POINTERMOVE|cn.POINTERDOUBLETAP),this._onLostFocus=()=>{this._pointA=this._pointB=null,n=0,r=null,this.onLostFocus()},this._contextMenuBind=e=>this.onContextMenu(e),i&&i.addEventListener("contextmenu",this._contextMenuBind,!1);const s=this.camera.getScene().getEngine().getHostWindow();s&&Yt.RegisterTopRootEvents(s,[{name:"blur",handler:this._onLostFocus}])}detachControl(){if(this._onLostFocus){const e=this.camera.getScene().getEngine().getHostWindow();e&&Yt.UnregisterTopRootEvents(e,[{name:"blur",handler:this._onLostFocus}])}if(this._observer){if(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._contextMenuBind){const e=this.camera.getScene().getEngine().getInputElement();e&&e.removeEventListener("contextmenu",this._contextMenuBind)}this._onLostFocus=null}this._altKey=!1,this._ctrlKey=!1,this._metaKey=!1,this._shiftKey=!1,this._buttonsPressed=0,this._currentActiveButton=-1}getClassName(){return"BaseCameraPointersInput"}getSimpleName(){return"pointers"}onDoubleTap(e){}onTouch(e,t,i){}onMultiTouch(e,t,i,n,r,s){}onContextMenu(e){e.preventDefault()}onButtonDown(e){}onButtonUp(e){}onLostFocus(){}}e([a()],Nn.prototype,"buttons",void 0);class Pn extends Nn{constructor(){super(...arguments),this.buttons=[0,1,2],this.angularSensibilityX=1e3,this.angularSensibilityY=1e3,this.pinchPrecision=12,this.pinchDeltaPercentage=0,this.useNaturalPinchZoom=!1,this.pinchZoom=!0,this.panningSensibility=1e3,this.multiTouchPanning=!0,this.multiTouchPanAndZoom=!0,this.pinchInwards=!0,this._isPanClick=!1,this._twoFingerActivityCount=0,this._isPinching=!1}getClassName(){return"ArcRotateCameraPointersInput"}_computeMultiTouchPanning(e,t){if(0!==this.panningSensibility&&e&&t){const i=t.x-e.x,n=t.y-e.y;this.camera.inertialPanningX+=-i/this.panningSensibility,this.camera.inertialPanningY+=n/this.panningSensibility}}_computePinchZoom(e,t){const i=this.camera.radius||Pn.MinimumRadiusForPinch;this.useNaturalPinchZoom?this.camera.radius=i*Math.sqrt(e)/Math.sqrt(t):this.pinchDeltaPercentage?this.camera.inertialRadiusOffset+=.001*(t-e)*i*this.pinchDeltaPercentage:this.camera.inertialRadiusOffset+=(t-e)/(this.pinchPrecision*(this.pinchInwards?1:-1)*(this.angularSensibilityX+this.angularSensibilityY)/2)}onTouch(e,t,i){0!==this.panningSensibility&&(this._ctrlKey&&this.camera._useCtrlForPanning||this._isPanClick)?(this.camera.inertialPanningX+=-t/this.panningSensibility,this.camera.inertialPanningY+=i/this.panningSensibility):(this.camera.inertialAlphaOffset-=t/this.angularSensibilityX,this.camera.inertialBetaOffset-=i/this.angularSensibilityY)}onDoubleTap(){this.camera.useInputToRestoreState&&this.camera.restoreState()}onMultiTouch(e,t,i,n,r,s){0===i&&null===r||0===n&&null===s||(this.multiTouchPanAndZoom?(this._computePinchZoom(i,n),this._computeMultiTouchPanning(r,s)):this.multiTouchPanning&&this.pinchZoom?(this._twoFingerActivityCount++,this._isPinching||this._twoFingerActivityCount<20&&Math.abs(Math.sqrt(n)-Math.sqrt(i))>this.camera.pinchToPanMaxDistance?(this._computePinchZoom(i,n),this._isPinching=!0):this._computeMultiTouchPanning(r,s)):this.multiTouchPanning?this._computeMultiTouchPanning(r,s):this.pinchZoom&&this._computePinchZoom(i,n))}onButtonDown(e){this._isPanClick=e.button===this.camera._panningMouseButton}onButtonUp(e){this._twoFingerActivityCount=0,this._isPinching=!1}onLostFocus(){this._isPanClick=!1,this._twoFingerActivityCount=0,this._isPinching=!1}}Pn.MinimumRadiusForPinch=.001,e([a()],Pn.prototype,"buttons",void 0),e([a()],Pn.prototype,"angularSensibilityX",void 0),e([a()],Pn.prototype,"angularSensibilityY",void 0),e([a()],Pn.prototype,"pinchPrecision",void 0),e([a()],Pn.prototype,"pinchDeltaPercentage",void 0),e([a()],Pn.prototype,"useNaturalPinchZoom",void 0),e([a()],Pn.prototype,"pinchZoom",void 0),e([a()],Pn.prototype,"panningSensibility",void 0),e([a()],Pn.prototype,"multiTouchPanning",void 0),e([a()],Pn.prototype,"multiTouchPanAndZoom",void 0),On.ArcRotateCameraPointersInput=Pn;class Ln{}Ln.KEYDOWN=1,Ln.KEYUP=2;class Fn{constructor(e,t){this.type=e,this.event=t}}class wn extends Fn{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}}class Un{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=Yt.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===Ln.KEYDOWN){if(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;t<this._keys.length;t++){const i=this._keys[t];-1!==this.keysLeft.indexOf(i)?this._ctrlPressed&&this.camera._useCtrlForPanning?e.inertialPanningX-=1/this.panningSensibility:e.inertialAlphaOffset-=this.angularSpeed:-1!==this.keysUp.indexOf(i)?this._ctrlPressed&&this.camera._useCtrlForPanning?e.inertialPanningY+=1/this.panningSensibility:this._altPressed&&this.useAltToZoom?e.inertialRadiusOffset+=1/this.zoomingSensibility:e.inertialBetaOffset-=this.angularSpeed:-1!==this.keysRight.indexOf(i)?this._ctrlPressed&&this.camera._useCtrlForPanning?e.inertialPanningX+=1/this.panningSensibility:e.inertialAlphaOffset+=this.angularSpeed:-1!==this.keysDown.indexOf(i)?this._ctrlPressed&&this.camera._useCtrlForPanning?e.inertialPanningY-=1/this.panningSensibility:this._altPressed&&this.useAltToZoom?e.inertialRadiusOffset-=1/this.zoomingSensibility:e.inertialBetaOffset+=this.angularSpeed:-1!==this.keysReset.indexOf(i)&&e.useInputToRestoreState&&e.restoreState()}}}getClassName(){return"ArcRotateCameraKeyboardMoveInput"}getSimpleName(){return"keyboard"}}e([a()],Un.prototype,"keysUp",void 0),e([a()],Un.prototype,"keysDown",void 0),e([a()],Un.prototype,"keysLeft",void 0),e([a()],Un.prototype,"keysRight",void 0),e([a()],Un.prototype,"keysReset",void 0),e([a()],Un.prototype,"panningSensibility",void 0),e([a()],Un.prototype,"zoomingSensibility",void 0),e([a()],Un.prototype,"useAltToZoom",void 0),e([a()],Un.prototype,"angularSpeed",void 0),On.ArcRotateCameraKeyboardMoveInput=Un,function(e){e[e.PointerMove=0]="PointerMove",e[e.PointerDown=1]="PointerDown",e[e.PointerUp=2]="PointerUp"}(yn||(yn={}));class Bn{}Bn.DOM_DELTA_PIXEL=0,Bn.DOM_DELTA_LINE=1,Bn.DOM_DELTA_PAGE=2;class Gn{constructor(){this.wheelPrecision=3,this.zoomToMouseLocation=!1,this.wheelDeltaPercentage=0,this.customComputeDeltaFromMouseWheel=null,this._viewOffset=new B(0,0,0),this._globalOffset=new B(0,0,0),this._inertialPanning=B.Zero()}_computeDeltaFromMouseWheelLegacyEvent(e,t){let i=0;const n=.01*e*this.wheelDeltaPercentage*t;return i=e>0?n/(1+this.wheelDeltaPercentage):n*(1+this.wheelDeltaPercentage),i}attachControl(e){e=Yt.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==cn.POINTERWHEEL)return;const i=t.event;let n=0;const r=i.deltaMode===Bn.DOM_DELTA_LINE?40:1,s=-i.deltaY*r;if(this.customComputeDeltaFromMouseWheel)n=this.customComputeDeltaFromMouseWheel(s,this,i);else if(this.wheelDeltaPercentage){if(n=this._computeDeltaFromMouseWheelLegacyEvent(s,this.camera.radius),n>0){let e=this.camera.radius,t=this.camera.inertialRadiusOffset+n;for(let i=0;i<20&&Math.abs(t)>.001;i++)e-=t,t*=this.camera.inertia;e=j.Clamp(e,0,Number.MAX_VALUE),n=this._computeDeltaFromMouseWheelLegacyEvent(s,e)}}else n=s/(40*this.wheelPrecision);n&&(this.zoomToMouseLocation?(this._hitPlane||this._updateHitPlane(),this._zoomToMouse(n)):this.camera.inertialRadiusOffset+=n),i.preventDefault&&(e||i.preventDefault())},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,cn.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=ei.FromPositionAndNormal(e.target,t)}_getPosition(){const e=this.camera,t=e.getScene(),i=t.createPickingRay(t.pointerX,t.pointerY,k.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=B.TransformNormal(this._viewOffset,e._cameraTransformMatrix),i.origin.addInPlace(this._globalOffset));let n=0;return this._hitPlane&&(n=i.intersectsPlane(this._hitPlane)??0),i.origin.addInPlace(i.direction.scaleInPlace(n))}_zoomToMouse(e){const t=this.camera,i=1-t.inertia;if(t.lowerRadiusLimit){const n=t.lowerRadiusLimit??0;t.radius-(t.inertialRadiusOffset+e)/i<n&&(e=(t.radius-n)*i-t.inertialRadiusOffset)}if(t.upperRadiusLimit){const n=t.upperRadiusLimit??0;t.radius-(t.inertialRadiusOffset+e)/i>n&&(e=(t.radius-n)*i-t.inertialRadiusOffset)}const n=e/i/t.radius,r=this._getPosition(),s=H.Vector3[6];r.subtractToRef(t.target,s),s.scaleInPlace(n),s.scaleInPlace(i),this._inertialPanning.addInPlace(s),t.inertialRadiusOffset+=e}_zeroIfClose(e){Math.abs(e.x)<A&&(e.x=0),Math.abs(e.y)<A&&(e.y=0),Math.abs(e.z)<A&&(e.z=0)}}e([a()],Gn.prototype,"wheelPrecision",void 0),e([a()],Gn.prototype,"zoomToMouseLocation",void 0),e([a()],Gn.prototype,"wheelDeltaPercentage",void 0),On.ArcRotateCameraMouseWheelInput=Gn;class Vn extends Dn{constructor(e){super(e)}addMouseWheel(){return this.add(new Gn),this}addPointers(){return this.add(new Pn),this}addKeyboard(){return this.add(new Un),this}}ae.AddNodeConstructor("ArcRotateCamera",((e,t)=>()=>new kn(e,0,0,1,B.Zero(),t)));class kn extends bn{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 k,this._upToYMatrix=new k,this._upVector=B.Zero()),e.normalize(),this._upVector.copyFrom(e),this.setMatUp()}get upVector(){return this._upVector}setMatUp(){k.RotationAlignToRef(B.UpReadOnly,this._upVector,this._yToUpMatrix),k.RotationAlignToRef(this._upVector,B.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 Mn,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 xn,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 fn,this.addBehavior(this._autoRotationBehavior)):this._autoRotationBehavior&&(this.removeBehavior(this._autoRotationBehavior),this._autoRotationBehavior=null))}constructor(e,t,i,n,r,s,a=!0){super(e,B.Zero(),s,a),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=B.Zero(),this.panningInertia=.9,this.zoomOnFactor=1,this.targetScreenOffset=U.Zero(),this.allowUpsideDown=!0,this.useInputToRestoreState=!0,this.restoreStateInterpolationFactor=0,this._viewMatrix=new k,this.panningAxis=new B(1,1,0),this._transformedDirection=new B,this.mapPanning=!1,this._progressiveRestore=!1,this.onMeshTargetChangedObservable=new g,this.checkCollisions=!1,this.collisionRadius=new B(.5,.5,.5),this._previousPosition=B.Zero(),this._collisionVelocity=B.Zero(),this._newPosition=B.Zero(),this._computationVector=B.Zero(),this._onCollisionPositionChange=(e,t,i=null)=>{i?(this.setPosition(t),this.onCollide&&this.onCollide(i)):this._previousPosition.copyFrom(this._position);const n=Math.cos(this.alpha),r=Math.sin(this.alpha),s=Math.cos(this.beta);let a=Math.sin(this.beta);0===a&&(a=1e-4);const o=this._getTargetPosition();this._computationVector.copyFromFloats(this.radius*n*a,this.radius*s,this.radius*r*a),o.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,o,l),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y),this._collisionTriggered=!1},this._target=B.Zero(),r&&this.setTarget(r),this.alpha=t,this.beta=i,this.radius=n,this.getViewMatrix(),this.inputs=new Vn(this),this.inputs.addKeyboard().addMouseWheel().addPointers()}_initCache(){super._initCache(),this._cache._target=new B(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=U.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)}const e=this._getLockedTargetPosition();return e||this._target}storeState(){return this._storedAlpha=this.alpha,this._storedBeta=this.beta,this._storedRadius=this.radius,this._storedTarget=this._getTargetPosition().clone(),this._storedTargetScreenOffset=this.targetScreenOffset.clone(),super.storeState()}_restoreStateValues(){return this.hasStateStored()&&this.restoreStateInterpolationFactor>A&&this.restoreStateInterpolationFactor<1?(this._progressiveRestore=!0,this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.inertialPanningX=0,this.inertialPanningY=0,!0):!!super._restoreStateValues()&&(this.setTarget(this._storedTarget.clone()),this.alpha=this._storedAlpha,this.beta=this._storedBeta,this.radius=this._storedRadius,this.targetScreenOffset=this._storedTargetScreenOffset.clone(),this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.inertialPanningX=0,this.inertialPanningY=0,!0)}_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,n=2){const r=arguments;t=Yt.BackCompatCameraNoPreventDefault(r),this._useCtrlForPanning=i,this._panningMouseButton=n,"boolean"==typeof r[0]&&(r.length>1&&(this._useCtrlForPanning=r[1]),r.length>2&&(this._panningMouseButton=r[2])),this.inputs.attachElement(t),this._reset=()=>{this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.inertialPanningX=0,this.inertialPanningY=0}}detachControl(){this.inputs.detachElement(),this._reset&&this._reset()}_checkInputs(){if(!this._collisionTriggered){if(this.inputs.checkInputs(),this._progressiveRestore){const e=this._scene.getEngine().getDeltaTime()/1e3,t=1-Math.pow(2,-e/this.restoreStateInterpolationFactor);this.setTarget(B.Lerp(this.getTarget(),this._storedTarget,t)),V.RotationAlphaBetaGammaToRef(this._storedAlpha,this._storedBeta,0,H.Quaternion[0]),V.RotationAlphaBetaGammaToRef(this.alpha,this.beta,0,H.Quaternion[1]),V.SlerpToRef(H.Quaternion[1],H.Quaternion[0],t,H.Quaternion[2]),H.Quaternion[2].normalize(),H.Quaternion[2].toAlphaBetaGammaToRef(H.Vector3[0]),this.alpha=H.Vector3[0].x,this.beta=H.Vector3[0].y,this.radius+=(this._storedRadius-this.radius)*t,U.LerpToRef(this.targetScreenOffset,this._storedTargetScreenOffset,t,this.targetScreenOffset),(B.DistanceSquared(this.getTarget(),this._storedTarget)<A&&H.Quaternion[2].equalsWithEpsilon(H.Quaternion[0])&&Math.pow(this._storedRadius-this.radius,2)<A&&U.Distance(this.targetScreenOffset,this._storedTargetScreenOffset)<A||0!==this.inertialAlphaOffset||0!==this.inertialBetaOffset||0!==this.inertialRadiusOffset||0!==this.inertialPanningX||0!==this.inertialPanningY)&&(this._progressiveRestore=!1)}if(0!==this.inertialAlphaOffset||0!==this.inertialBetaOffset||0!==this.inertialRadiusOffset){const e=this.invertRotation?-1:1,t=this._calculateHandednessMultiplier();let i=this.inertialAlphaOffset*t;this.beta<0&&(i*=-1),this.alpha+=i*e,this.beta+=this.inertialBetaOffset*e,this.radius-=this.inertialRadiusOffset,this.inertialAlphaOffset*=this.inertia,this.inertialBetaOffset*=this.inertia,this.inertialRadiusOffset*=this.inertia,Math.abs(this.inertialAlphaOffset)<A&&(this.inertialAlphaOffset=0),Math.abs(this.inertialBetaOffset)<A&&(this.inertialBetaOffset=0),Math.abs(this.inertialRadiusOffset)<this.speed*A&&(this.inertialRadiusOffset=0)}if(0!==this.inertialPanningX||0!==this.inertialPanningY){const e=new B(this.inertialPanningX,this.inertialPanningY,this.inertialPanningY);if(this._viewMatrix.invertToRef(this._cameraTransformMatrix),e.multiplyInPlace(this.panningAxis),B.TransformNormalToRef(e,this._cameraTransformMatrix,this._transformedDirection),this.mapPanning){const e=this.upVector,t=B.CrossToRef(this._transformedDirection,e,this._transformedDirection);B.CrossToRef(e,t,this._transformedDirection)}else this.panningAxis.y||(this._transformedDirection.y=0);if(!this._targetHost)if(this.panningDistanceLimit){this._transformedDirection.addInPlace(this._target);B.DistanceSquared(this._transformedDirection,this.panningOriginTarget)<=this.panningDistanceLimit*this.panningDistanceLimit&&this._target.copyFrom(this._transformedDirection)}else{if(this.parent){const e=H.Matrix[0];this.parent.getWorldMatrix().getRotationMatrixToRef(e),e.transposeToRef(e),B.TransformCoordinatesToRef(this._transformedDirection,e,this._transformedDirection)}this._target.addInPlace(this._transformedDirection)}this.inertialPanningX*=this.panningInertia,this.inertialPanningY*=this.panningInertia,Math.abs(this.inertialPanningX)<this.speed*A&&(this.inertialPanningX=0),Math.abs(this.inertialPanningY)<this.speed*A&&(this.inertialPanningY=0)}this._checkLimits(),super._checkInputs()}}_checkLimits(){null===this.lowerBetaLimit||void 0===this.lowerBetaLimit?this.allowUpsideDown&&this.beta>Math.PI&&(this.beta=this.beta-2*Math.PI):this.beta<this.lowerBetaLimit&&(this.beta=this.lowerBetaLimit),null===this.upperBetaLimit||void 0===this.upperBetaLimit?this.allowUpsideDown&&this.beta<-Math.PI&&(this.beta=this.beta+2*Math.PI):this.beta>this.upperBetaLimit&&(this.beta=this.upperBetaLimit),null!==this.lowerAlphaLimit&&this.alpha<this.lowerAlphaLimit&&(this.alpha=this.lowerAlphaLimit),null!==this.upperAlphaLimit&&this.alpha>this.upperAlphaLimit&&(this.alpha=this.upperAlphaLimit),null!==this.lowerRadiusLimit&&this.radius<this.lowerRadiusLimit&&(this.radius=this.lowerRadiusLimit,this.inertialRadiusOffset=0),null!==this.upperRadiusLimit&&this.radius>this.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||B.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,n=!1){if(n=this.overrideCloneAlphaBetaRadius??n,e.computeWorldMatrix)t&&e.getBoundingInfo?this._targetBoundingCenter=e.getBoundingInfo().boundingBox.centerWorld.clone():this._targetBoundingCenter=null,e.computeWorldMatrix(),this._targetHost=e,this._target=this._getTargetPosition(),this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);else{const t=e,n=this._getTargetPosition();if(n&&!i&&n.equals(t))return;this._targetHost=null,this._target=t,this._targetBoundingCenter=null,this.onMeshTargetChangedObservable.notifyObservers(null)}n||this.rebuildAnglesAndRadius()}_getViewMatrix(){const e=Math.cos(this.alpha),t=Math.sin(this.alpha),i=Math.cos(this.beta);let n=Math.sin(this.beta);0===n&&(n=1e-4),0===this.radius&&(this.radius=1e-4);const r=this._getTargetPosition();if(this._computationVector.copyFromFloats(this.radius*e*n,this.radius*i,this.radius*t*n),0===this._upVector.x&&1===this._upVector.y&&0===this._upVector.z||B.TransformCoordinatesToRef(this._computationVector,this._yToUpMatrix,this._computationVector),r.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&&n<0&&(e=e.negate()),this._computeViewMatrix(this._position,r,e),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y)}return this._currentTarget=r,this._viewMatrix}zoomOn(e,t=!1){e=e||this.getScene().meshes;const i=ln.MinMax(e);let n=this._calculateLowerRadiusFromModelBoundingSphere(i.min,i.max);n=Math.max(Math.min(n,this.upperRadiusLimit||Number.MAX_VALUE),this.lowerRadiusLimit||0),this.radius=n*this.zoomOnFactor,this.focusOn({min:i.min,max:i.max,distance:n},t)}focusOn(e,t=!1){let i,n;if(void 0===e.min){const t=e||this.getScene().meshes;i=ln.MinMax(t),n=B.Distance(i.min,i.max)}else{i=e,n=e.distance}this._target=ln.Center(i),t||(this.maxZ=2*n)}createRigCamera(e,t){let i=0;switch(this.cameraRigMode){case ii.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case ii.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case ii.RIG_MODE_STEREOSCOPIC_OVERUNDER:case ii.RIG_MODE_STEREOSCOPIC_INTERLACED:case ii.RIG_MODE_VR:i=this._cameraRigParams.stereoHalfAngle*(0===t?1:-1);break;case ii.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:i=this._cameraRigParams.stereoHalfAngle*(0===t?-1:1)}const n=new kn(e,this.alpha+i,this.beta,this.radius,this._target,this.getScene());return n._cameraRigParams={},n.isRigCamera=!0,n.rigParent=this,n.upVector=this.upVector,n.mode=this.mode,n.orthoLeft=this.orthoLeft,n.orthoRight=this.orthoRight,n.orthoBottom=this.orthoBottom,n.orthoTop=this.orthoTop,n}_updateRigCameras(){const e=this._rigCameras[0],t=this._rigCameras[1];switch(e.beta=t.beta=this.beta,this.cameraRigMode){case ii.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case ii.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case ii.RIG_MODE_STEREOSCOPIC_OVERUNDER:case ii.RIG_MODE_STEREOSCOPIC_INTERLACED:case ii.RIG_MODE_VR:e.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle;break;case ii.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 n=B.Distance(e,t),r=this.getScene().getEngine().getAspectRatio(this),s=Math.tan(this.fov/2),a=s*r,o=.5*n*i,l=o*Math.sqrt(1+1/(a*a)),c=o*Math.sqrt(1+1/(s*s));return Math.max(l,c)}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"ArcRotateCamera"}}e([a()],kn.prototype,"alpha",void 0),e([a()],kn.prototype,"beta",void 0),e([a()],kn.prototype,"radius",void 0),e([a()],kn.prototype,"overrideCloneAlphaBetaRadius",void 0),e([h("target")],kn.prototype,"_target",void 0),e([d("targetHost")],kn.prototype,"_targetHost",void 0),e([a()],kn.prototype,"inertialAlphaOffset",void 0),e([a()],kn.prototype,"inertialBetaOffset",void 0),e([a()],kn.prototype,"inertialRadiusOffset",void 0),e([a()],kn.prototype,"lowerAlphaLimit",void 0),e([a()],kn.prototype,"upperAlphaLimit",void 0),e([a()],kn.prototype,"lowerBetaLimit",void 0),e([a()],kn.prototype,"upperBetaLimit",void 0),e([a()],kn.prototype,"lowerRadiusLimit",void 0),e([a()],kn.prototype,"upperRadiusLimit",void 0),e([a()],kn.prototype,"inertialPanningX",void 0),e([a()],kn.prototype,"inertialPanningY",void 0),e([a()],kn.prototype,"pinchToPanMaxDistance",void 0),e([a()],kn.prototype,"panningDistanceLimit",void 0),e([h()],kn.prototype,"panningOriginTarget",void 0),e([a()],kn.prototype,"panningInertia",void 0),e([a()],kn.prototype,"zoomToMouseLocation",null),e([a()],kn.prototype,"zoomOnFactor",void 0),e([c()],kn.prototype,"targetScreenOffset",void 0),e([a()],kn.prototype,"allowUpsideDown",void 0),e([a()],kn.prototype,"useInputToRestoreState",void 0),e([a()],kn.prototype,"restoreStateInterpolationFactor",void 0),M("BABYLON.ArcRotateCamera",kn);class Xn extends ae{get range(){return this._range}set range(e){this._range=e,this._inverseSquaredRange=1/(this.range*this.range)}get intensityMode(){return this._intensityMode}set intensityMode(e){this._intensityMode=e,this._computePhotometricScale()}get radius(){return this._radius}set radius(e){this._radius=e,this._computePhotometricScale()}get shadowEnabled(){return this._shadowEnabled}set shadowEnabled(e){this._shadowEnabled!==e&&(this._shadowEnabled=e,this._markMeshesAsLightDirty())}get includedOnlyMeshes(){return this._includedOnlyMeshes}set includedOnlyMeshes(e){this._includedOnlyMeshes=e,this._hookArrayForIncludedOnly(e)}get excludedMeshes(){return this._excludedMeshes}set excludedMeshes(e){this._excludedMeshes=e,this._hookArrayForExcluded(e)}get excludeWithLayerMask(){return this._excludeWithLayerMask}set excludeWithLayerMask(e){this._excludeWithLayerMask=e,this._resyncMeshes()}get includeOnlyWithLayerMask(){return this._includeOnlyWithLayerMask}set includeOnlyWithLayerMask(e){this._includeOnlyWithLayerMask=e,this._resyncMeshes()}get lightmapMode(){return this._lightmapMode}set lightmapMode(e){this._lightmapMode!==e&&(this._lightmapMode=e,this._markMeshesAsLightDirty())}getViewMatrix(e){return null}getProjectionMatrix(e,t){return null}constructor(e,t){super(e,t,!1),this.diffuse=new ee(1,1,1),this.specular=new ee(1,1,1),this.falloffType=Xn.FALLOFF_DEFAULT,this.intensity=1,this._range=Number.MAX_VALUE,this._inverseSquaredRange=0,this._photometricScale=1,this._intensityMode=Xn.INTENSITYMODE_AUTOMATIC,this._radius=1e-5,this.renderPriority=0,this._shadowEnabled=!0,this._excludeWithLayerMask=0,this._includeOnlyWithLayerMask=0,this._lightmapMode=0,this._shadowGenerators=null,this._excludedMeshesIds=new Array,this._includedOnlyMeshesIds=new Array,this._isLight=!0,this.getScene().addLight(this),this._uniformBuffer=new Pi(this.getScene().getEngine(),void 0,void 0,e),this._buildUniformLayout(),this.includedOnlyMeshes=[],this.excludedMeshes=[],this._resyncMeshes()}transferTexturesToEffect(e,t){return this}_bindLight(e,t,i,n,r=!0){const s=e.toString();let a=!1;if(this._uniformBuffer.bindToEffect(i,"Light"+s),this._renderId!==t.getRenderId()||this._lastUseSpecular!==n||!this._uniformBuffer.useUbo){this._renderId=t.getRenderId(),this._lastUseSpecular=n;const e=this.getScaledIntensity();this.transferToEffect(i,s),this.diffuse.scaleToRef(e,ie.Color3[0]),this._uniformBuffer.updateColor4("vLightDiffuse",ie.Color3[0],this.range,s),n&&(this.specular.scaleToRef(e,ie.Color3[1]),this._uniformBuffer.updateColor4("vLightSpecular",ie.Color3[1],this.radius,s)),a=!0}if(this.transferTexturesToEffect(i,s),t.shadowsEnabled&&this.shadowEnabled&&r){const e=this.getShadowGenerator(t.activeCamera)??this.getShadowGenerator();e&&(e.bindShadowLight(s,i),a=!0)}a?this._uniformBuffer.update():this._uniformBuffer.bindUniformBuffer()}getClassName(){return"Light"}toString(e){let t="Name: "+this.name;if(t+=", type: "+["Point","Directional","Spot","Hemispheric"][this.getTypeID()],this.animations)for(let i=0;i<this.animations.length;i++)t+=", animation[0]: "+this.animations[i].toString(e);return t}_syncParentEnabledState(){super._syncParentEnabledState(),this.isDisposed()||this._resyncMeshes()}setEnabled(e){super.setEnabled(e),this._resyncMeshes()}getShadowGenerator(e=null){return null===this._shadowGenerators?null:this._shadowGenerators.get(e)??null}getShadowGenerators(){return this._shadowGenerators}getAbsolutePosition(){return B.Zero()}canAffectMesh(e){return!e||!(this.includedOnlyMeshes&&this.includedOnlyMeshes.length>0&&-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=Xn.GetConstructorFromName(this.getTypeID(),e,this.getScene());if(!i)return null;const n=re.Clone(i,this);return e&&(n.name=e),t&&(n.parent=t),n.setEnabled(this.isEnabled()),this.onClonedObservable.notifyObservers(n),n}serialize(){const e=re.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)}))),re.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.isEnabled=this.isEnabled(),e}static GetConstructorFromName(e,t,i){const n=ae.Construct("Light_Type_"+e,t,i);return n||null}static Parse(e,t){const i=Xn.GetConstructorFromName(e.type,e.name,t);if(!i)return null;const n=re.Parse(i,e,t);if(e.excludedMeshesIds&&(n._excludedMeshesIds=e.excludedMeshesIds),e.includedOnlyMeshesIds&&(n._includedOnlyMeshesIds=e.includedOnlyMeshesIds),void 0!==e.parentId&&(n._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(n._waitingParentInstanceIndex=e.parentInstanceIndex),void 0!==e.falloffType&&(n.falloffType=e.falloffType),void 0!==e.lightmapMode&&(n.lightmapMode=e.lightmapMode),e.animations){for(let t=0;t<e.animations.length;t++){const i=e.animations[t],r=x("BABYLON.Animation");r&&n.animations.push(r.Parse(i))}ae.ParseAnimationRanges(n,e,t)}return e.autoAnimate&&t.beginAnimation(n,e.autoAnimateFrom,e.autoAnimateTo,e.autoAnimateLoop,e.autoAnimateSpeed||1),void 0!==e.isEnabled&&n.setEnabled(e.isEnabled),n}_hookArrayForExcluded(e){const t=e.push;e.push=(...i)=>{const n=t.apply(e,i);for(const e of i)e._resyncLightSource(this);return n};const i=e.splice;e.splice=(t,n)=>{const r=i.apply(e,[t,n]);for(const e of r)e._resyncLightSource(this);return r};for(const t of e)t._resyncLightSource(this)}_hookArrayForIncludedOnly(e){const t=e.push;e.push=(...i)=>{const n=t.apply(e,i);return this._resyncMeshes(),n};const i=e.splice;e.splice=(t,n)=>{const r=i.apply(e,[t,n]);return this._resyncMeshes(),r},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===Xn.INTENSITYMODE_AUTOMATIC&&(i=t===Xn.LIGHTTYPEID_DIRECTIONALLIGHT?Xn.INTENSITYMODE_ILLUMINANCE:Xn.INTENSITYMODE_LUMINOUSINTENSITY),t){case Xn.LIGHTTYPEID_POINTLIGHT:case Xn.LIGHTTYPEID_SPOTLIGHT:switch(i){case Xn.INTENSITYMODE_LUMINOUSPOWER:e=1/(4*Math.PI);break;case Xn.INTENSITYMODE_LUMINOUSINTENSITY:e=1;break;case Xn.INTENSITYMODE_LUMINANCE:e=this.radius*this.radius}break;case Xn.LIGHTTYPEID_DIRECTIONALLIGHT:switch(i){case Xn.INTENSITYMODE_ILLUMINANCE:e=1;break;case Xn.INTENSITYMODE_LUMINANCE:{let t=this.radius;t=Math.max(t,.001);e=2*Math.PI*(1-Math.cos(t));break}}break;case Xn.LIGHTTYPEID_HEMISPHERICLIGHT:e=1}return e}_reorderLightsInScene(){const e=this.getScene();0!=this._renderPriority&&(e.requireLightSorting=!0),this.getScene().sortLightsByPriority()}}Xn.FALLOFF_DEFAULT=Xi.FALLOFF_DEFAULT,Xn.FALLOFF_PHYSICAL=Xi.FALLOFF_PHYSICAL,Xn.FALLOFF_GLTF=Xi.FALLOFF_GLTF,Xn.FALLOFF_STANDARD=Xi.FALLOFF_STANDARD,Xn.LIGHTMAP_DEFAULT=Xi.LIGHTMAP_DEFAULT,Xn.LIGHTMAP_SPECULAR=Xi.LIGHTMAP_SPECULAR,Xn.LIGHTMAP_SHADOWSONLY=Xi.LIGHTMAP_SHADOWSONLY,Xn.INTENSITYMODE_AUTOMATIC=Xi.INTENSITYMODE_AUTOMATIC,Xn.INTENSITYMODE_LUMINOUSPOWER=Xi.INTENSITYMODE_LUMINOUSPOWER,Xn.INTENSITYMODE_LUMINOUSINTENSITY=Xi.INTENSITYMODE_LUMINOUSINTENSITY,Xn.INTENSITYMODE_ILLUMINANCE=Xi.INTENSITYMODE_ILLUMINANCE,Xn.INTENSITYMODE_LUMINANCE=Xi.INTENSITYMODE_LUMINANCE,Xn.LIGHTTYPEID_POINTLIGHT=Xi.LIGHTTYPEID_POINTLIGHT,Xn.LIGHTTYPEID_DIRECTIONALLIGHT=Xi.LIGHTTYPEID_DIRECTIONALLIGHT,Xn.LIGHTTYPEID_SPOTLIGHT=Xi.LIGHTTYPEID_SPOTLIGHT,Xn.LIGHTTYPEID_HEMISPHERICLIGHT=Xi.LIGHTTYPEID_HEMISPHERICLIGHT,e([l()],Xn.prototype,"diffuse",void 0),e([l()],Xn.prototype,"specular",void 0),e([a()],Xn.prototype,"falloffType",void 0),e([a()],Xn.prototype,"intensity",void 0),e([a()],Xn.prototype,"range",null),e([a()],Xn.prototype,"intensityMode",null),e([a()],Xn.prototype,"radius",null),e([a()],Xn.prototype,"_renderPriority",void 0),e([s("_reorderLightsInScene")],Xn.prototype,"renderPriority",void 0),e([a("shadowEnabled")],Xn.prototype,"_shadowEnabled",void 0),e([a("excludeWithLayerMask")],Xn.prototype,"_excludeWithLayerMask",void 0),e([a("includeOnlyWithLayerMask")],Xn.prototype,"_includeOnlyWithLayerMask",void 0),e([a("lightmapMode")],Xn.prototype,"_lightmapMode",void 0),ae.AddNodeConstructor("Light_Type_3",((e,t)=>()=>new Hn(e,B.Zero(),t)));class Hn extends Xn{constructor(e,t,i){super(e,i),this.groundColor=new ee(0,0,0),this.direction=t||B.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=B.Normalize(e.subtract(B.Zero())),this.direction}getShadowGenerator(){return null}transferToEffect(e,t){const i=B.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=B.Normalize(this.direction);return e.setFloat3(t,i.x,i.y,i.z),this}computeWorldMatrix(){return this._worldMatrix||(this._worldMatrix=k.Identity()),this._worldMatrix}getTypeID(){return Xn.LIGHTTYPEID_HEMISPHERICLIGHT}prepareLightSpecificDefines(e,t){e["HEMILIGHT"+t]=!0}}e([l()],Hn.prototype,"groundColor",void 0),e([h()],Hn.prototype,"direction",void 0),M("BABYLON.HemisphericLight",Hn);class Wn{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}}class zn{constructor(){this.rootNodes=[],this.cameras=[],this.lights=[],this.meshes=[],this.skeletons=[],this.particleSystems=[],this.animations=[],this.animationGroups=[],this.multiMaterials=[],this.materials=[],this.morphTargetManagers=[],this.geometries=[],this.transformNodes=[],this.actionManagers=[],this.textures=[],this._environmentTexture=null,this.postProcesses=[]}static AddParser(e,t){this._BabylonFileParsers[e]=t}static GetParser(e){return this._BabylonFileParsers[e]?this._BabylonFileParsers[e]:null}static AddIndividualParser(e,t){this._IndividualBabylonFileParsers[e]=t}static GetIndividualParser(e){return this._IndividualBabylonFileParsers[e]?this._IndividualBabylonFileParsers[e]:null}static Parse(e,t,i,n){for(const r in this._BabylonFileParsers)Object.prototype.hasOwnProperty.call(this._BabylonFileParsers,r)&&this._BabylonFileParsers[r](e,t,i,n)}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture=e}getNodes(){let e=[];return e=e.concat(this.meshes),e=e.concat(this.lights),e=e.concat(this.cameras),e=e.concat(this.transformNodes),this.skeletons.forEach((t=>e=e.concat(t.bones))),e}}function Yn(e){e.push("vCameraColorCurveNeutral","vCameraColorCurvePositive","vCameraColorCurveNegative")}zn._BabylonFileParsers={},zn._IndividualBabylonFileParsers={},M("BABYLON.AbstractScene",zn);class Kn{constructor(){this._dirty=!0,this._tempColor=new te(0,0,0,0),this._globalCurve=new te(0,0,0,0),this._highlightsCurve=new te(0,0,0,0),this._midtonesCurve=new te(0,0,0,0),this._shadowsCurve=new te(0,0,0,0),this._positiveCurve=new te(0,0,0,0),this._negativeCurve=new te(0,0,0,0),this._globalHue=30,this._globalDensity=0,this._globalSaturation=0,this._globalExposure=0,this._highlightsHue=30,this._highlightsDensity=0,this._highlightsSaturation=0,this._highlightsExposure=0,this._midtonesHue=30,this._midtonesDensity=0,this._midtonesSaturation=0,this._midtonesExposure=0,this._shadowsHue=30,this._shadowsDensity=0,this._shadowsSaturation=0,this._shadowsExposure=0}get globalHue(){return this._globalHue}set globalHue(e){this._globalHue=e,this._dirty=!0}get globalDensity(){return this._globalDensity}set globalDensity(e){this._globalDensity=e,this._dirty=!0}get globalSaturation(){return this._globalSaturation}set globalSaturation(e){this._globalSaturation=e,this._dirty=!0}get globalExposure(){return this._globalExposure}set globalExposure(e){this._globalExposure=e,this._dirty=!0}get highlightsHue(){return this._highlightsHue}set highlightsHue(e){this._highlightsHue=e,this._dirty=!0}get highlightsDensity(){return this._highlightsDensity}set highlightsDensity(e){this._highlightsDensity=e,this._dirty=!0}get highlightsSaturation(){return this._highlightsSaturation}set highlightsSaturation(e){this._highlightsSaturation=e,this._dirty=!0}get highlightsExposure(){return this._highlightsExposure}set highlightsExposure(e){this._highlightsExposure=e,this._dirty=!0}get midtonesHue(){return this._midtonesHue}set midtonesHue(e){this._midtonesHue=e,this._dirty=!0}get midtonesDensity(){return this._midtonesDensity}set midtonesDensity(e){this._midtonesDensity=e,this._dirty=!0}get midtonesSaturation(){return this._midtonesSaturation}set midtonesSaturation(e){this._midtonesSaturation=e,this._dirty=!0}get midtonesExposure(){return this._midtonesExposure}set midtonesExposure(e){this._midtonesExposure=e,this._dirty=!0}get shadowsHue(){return this._shadowsHue}set shadowsHue(e){this._shadowsHue=e,this._dirty=!0}get shadowsDensity(){return this._shadowsDensity}set shadowsDensity(e){this._shadowsDensity=e,this._dirty=!0}get shadowsSaturation(){return this._shadowsSaturation}set shadowsSaturation(e){this._shadowsSaturation=e,this._dirty=!0}get shadowsExposure(){return this._shadowsExposure}set shadowsExposure(e){this._shadowsExposure=e,this._dirty=!0}getClassName(){return"ColorCurves"}static Bind(e,t,i="vCameraColorCurvePositive",n="vCameraColorCurveNeutral",r="vCameraColorCurveNegative"){e._dirty&&(e._dirty=!1,e._getColorGradingDataToRef(e._globalHue,e._globalDensity,e._globalSaturation,e._globalExposure,e._globalCurve),e._getColorGradingDataToRef(e._highlightsHue,e._highlightsDensity,e._highlightsSaturation,e._highlightsExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._highlightsCurve),e._getColorGradingDataToRef(e._midtonesHue,e._midtonesDensity,e._midtonesSaturation,e._midtonesExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._midtonesCurve),e._getColorGradingDataToRef(e._shadowsHue,e._shadowsDensity,e._shadowsSaturation,e._shadowsExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._shadowsCurve),e._highlightsCurve.subtractToRef(e._midtonesCurve,e._positiveCurve),e._midtonesCurve.subtractToRef(e._shadowsCurve,e._negativeCurve)),t&&(t.setFloat4(i,e._positiveCurve.r,e._positiveCurve.g,e._positiveCurve.b,e._positiveCurve.a),t.setFloat4(n,e._midtonesCurve.r,e._midtonesCurve.g,e._midtonesCurve.b,e._midtonesCurve.a),t.setFloat4(r,e._negativeCurve.r,e._negativeCurve.g,e._negativeCurve.b,e._negativeCurve.a))}_getColorGradingDataToRef(e,t,i,n,r){null!=e&&(e=Kn._Clamp(e,0,360),t=Kn._Clamp(t,-100,100),i=Kn._Clamp(i,-100,100),n=Kn._Clamp(n,-100,100),t=Kn._ApplyColorGradingSliderNonlinear(t),t*=.5,n=Kn._ApplyColorGradingSliderNonlinear(n),t<0&&(t*=-1,e=(e+180)%360),Kn._FromHSBToRef(e,t,50+.25*n,r),r.scaleToRef(2,r),r.a=1+.01*i)}static _ApplyColorGradingSliderNonlinear(e){e/=100;let t=Math.abs(e);return t=Math.pow(t,2),e<0&&(t*=-1),t*=100,t}static _FromHSBToRef(e,t,i,n){let r=Kn._Clamp(e,0,360);const s=Kn._Clamp(t/100,0,1),a=Kn._Clamp(i/100,0,1);if(0===s)n.r=a,n.g=a,n.b=a;else{r/=60;const e=Math.floor(r),t=r-e,i=a*(1-s),o=a*(1-s*t),l=a*(1-s*(1-t));switch(e){case 0:n.r=a,n.g=l,n.b=i;break;case 1:n.r=o,n.g=a,n.b=i;break;case 2:n.r=i,n.g=a,n.b=l;break;case 3:n.r=i,n.g=o,n.b=a;break;case 4:n.r=l,n.g=i,n.b=a;break;default:n.r=a,n.g=i,n.b=o}}n.a=1}static _Clamp(e,t,i){return Math.min(Math.max(e,t),i)}clone(){return re.Clone((()=>new Kn),this)}serialize(){return re.Serialize(this)}static Parse(e){return re.Parse((()=>new Kn),e,null,null)}}Kn.PrepareUniforms=Yn,e([a()],Kn.prototype,"_globalHue",void 0),e([a()],Kn.prototype,"_globalDensity",void 0),e([a()],Kn.prototype,"_globalSaturation",void 0),e([a()],Kn.prototype,"_globalExposure",void 0),e([a()],Kn.prototype,"_highlightsHue",void 0),e([a()],Kn.prototype,"_highlightsDensity",void 0),e([a()],Kn.prototype,"_highlightsSaturation",void 0),e([a()],Kn.prototype,"_highlightsExposure",void 0),e([a()],Kn.prototype,"_midtonesHue",void 0),e([a()],Kn.prototype,"_midtonesDensity",void 0),e([a()],Kn.prototype,"_midtonesSaturation",void 0),e([a()],Kn.prototype,"_midtonesExposure",void 0),re._ColorCurvesParser=Kn.Parse;class qn{constructor(){this.colorCurves=new Kn,this._colorCurvesEnabled=!1,this._colorGradingEnabled=!1,this._colorGradingWithGreenDepth=!0,this._colorGradingBGR=!0,this._exposure=1,this._toneMappingEnabled=!1,this._toneMappingType=qn.TONEMAPPING_STANDARD,this._contrast=1,this.vignetteStretch=0,this.vignetteCenterX=0,this.vignetteCenterY=0,this.vignetteWeight=1.5,this.vignetteColor=new te(0,0,0,0),this.vignetteCameraFov=.5,this._vignetteBlendMode=qn.VIGNETTEMODE_MULTIPLY,this._vignetteEnabled=!1,this._ditheringEnabled=!1,this._ditheringIntensity=1/255,this._skipFinalColorClamp=!1,this._applyByPostProcess=!1,this._isEnabled=!0,this.onUpdateParameters=new g}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===qn._VIGNETTEMODE_MULTIPLY,e.VIGNETTEBLENDMODEOPAQUE=!e.VIGNETTEBLENDMODEMULTIPLY,this._toneMappingEnabled)switch(this._toneMappingType){case qn.TONEMAPPING_KHR_PBR_NEUTRAL:e.TONEMAPPING=3;break;case qn.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&&Kn.Bind(this.colorCurves,e),this._vignetteEnabled||this._ditheringEnabled){const i=1/e.getEngine().getRenderWidth(),n=1/e.getEngine().getRenderHeight();if(e.setFloat2("vInverseScreenSize",i,n),this._ditheringEnabled&&e.setFloat("ditherIntensity",.5*this._ditheringIntensity),this._vignetteEnabled){const r=null!=t?t:n/i;let s=Math.tan(.5*this.vignetteCameraFov),a=s*r;const o=Math.sqrt(a*s);a=kt(a,o,this.vignetteStretch),s=kt(s,o,this.vignetteStretch),e.setFloat4("vignetteSettings1",a,s,-a*this.vignetteCenterX,-s*this.vignetteCenterY);const l=-2*this.vignetteWeight;e.setFloat4("vignetteSettings2",this.vignetteColor.r,this.vignetteColor.g,this.vignetteColor.b,l)}}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 re.Clone((()=>new qn),this)}serialize(){return re.Serialize(this)}static Parse(e){const t=re.Parse((()=>new qn),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}}qn.TONEMAPPING_STANDARD=0,qn.TONEMAPPING_ACES=1,qn.TONEMAPPING_KHR_PBR_NEUTRAL=2,qn.PrepareUniforms=function(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&&Yn(e),t.DITHER&&e.push("ditherIntensity")},qn.PrepareSamplers=function(e,t){t.COLORGRADING&&e.push("txColorTransform")},qn._VIGNETTEMODE_MULTIPLY=0,qn._VIGNETTEMODE_OPAQUE=1,e([function(e){return r(7,e)}()],qn.prototype,"colorCurves",void 0),e([a()],qn.prototype,"_colorCurvesEnabled",void 0),e([o("colorGradingTexture")],qn.prototype,"_colorGradingTexture",void 0),e([a()],qn.prototype,"_colorGradingEnabled",void 0),e([a()],qn.prototype,"_colorGradingWithGreenDepth",void 0),e([a()],qn.prototype,"_colorGradingBGR",void 0),e([a()],qn.prototype,"_exposure",void 0),e([a()],qn.prototype,"_toneMappingEnabled",void 0),e([a()],qn.prototype,"_toneMappingType",void 0),e([a()],qn.prototype,"_contrast",void 0),e([a()],qn.prototype,"vignetteStretch",void 0),e([a()],qn.prototype,"vignetteCenterX",void 0),e([a()],qn.prototype,"vignetteCenterY",void 0),e([a()],qn.prototype,"vignetteWeight",void 0),e([u()],qn.prototype,"vignetteColor",void 0),e([a()],qn.prototype,"vignetteCameraFov",void 0),e([a()],qn.prototype,"_vignetteBlendMode",void 0),e([a()],qn.prototype,"_vignetteEnabled",void 0),e([a()],qn.prototype,"_ditheringEnabled",void 0),e([a()],qn.prototype,"_ditheringIntensity",void 0),e([a()],qn.prototype,"_skipFinalColorClamp",void 0),e([a()],qn.prototype,"_applyByPostProcess",void 0),e([a()],qn.prototype,"_isEnabled",void 0),re._ImageProcessingConfigurationParser=qn.Parse,M("BABYLON.ImageProcessingConfiguration",qn);class jn{constructor(e,t,i,n,r,s){this.source=e,this.pointerX=t,this.pointerY=i,this.meshUnderPointer=n,this.sourceEvent=r,this.additionalData=s}static CreateNew(e,t,i){const n=e.getScene();return new jn(e,n.pointerX,n.pointerY,n.meshUnderPointer||e,t,i)}static CreateNewFromSprite(e,t,i,n){return new jn(e,t.pointerX,t.pointerY,t.meshUnderPointer,i,n)}static CreateNewFromScene(e,t){return new jn(null,e.pointerX,e.pointerY,e.meshUnderPointer,t)}static CreateNewFromPrimitive(e,t,i,n){return new jn(e,t.x,t.y,null,i,n)}}class Qn{constructor(e){this._vertexBuffers={},this._scene=e}_prepareBuffers(){if(this._vertexBuffers[si.PositionKind])return;const e=[];e.push(1,1),e.push(-1,1),e.push(-1,-1),e.push(1,-1),this._vertexBuffers[si.PositionKind]=new si(this._scene.getEngine(),e,si.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[si.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,n=0,r=0,s=!1){const a=this._scene.getEngine();for(let o=0;o<e.length;o++){o<e.length-1?e[o+1].activate(this._scene.activeCamera,t?.texture):(t?a.bindFramebuffer(t,n,void 0,void 0,i,r):s||a.restoreDefaultFramebuffer(),a._debugInsertMarker?.(`post process ${e[o].name} output`));const l=e[o],c=l.apply();c&&(l.onBeforeRenderObservable.notifyObservers(c),this._prepareBuffers(),a.bindBuffers(this._vertexBuffers,this._indexBuffer,c),a.drawElementsType(Ze.MATERIAL_TriangleFillMode,0,6),l.onAfterRenderObservable.notifyObservers(c))}a.setDepthBuffer(!0),a.setDepthWrite(!0)}_finalizeFrame(e,t,i,n,r=!1){const s=this._scene.activeCamera;if(!s)return;if(0===(n=n||s._postProcesses.filter((e=>null!=e))).length||!this._scene.postProcessesEnabled)return;const a=this._scene.getEngine();for(let o=0,l=n.length;o<l;o++){const c=n[o];if(o<l-1?c._outputTexture=n[o+1].activate(s,t?.texture):(t?(a.bindFramebuffer(t,i,void 0,void 0,r),c._outputTexture=t):(a.restoreDefaultFramebuffer(),c._outputTexture=null),a._debugInsertMarker?.(`post process ${n[o].name} output`)),e)break;const h=c.apply();h&&(c.onBeforeRenderObservable.notifyObservers(h),this._prepareBuffers(),a.bindBuffers(this._vertexBuffers,this._indexBuffer,h),a.drawElementsType(Ze.MATERIAL_TriangleFillMode,0,6),c.onAfterRenderObservable.notifyObservers(h))}a.setDepthBuffer(!0),a.setDepthWrite(!0),a.setAlphaMode(Ze.ALPHA_DISABLE)}dispose(){const e=this._vertexBuffers[si.PositionKind];e&&(e.dispose(),this._vertexBuffers[si.PositionKind]=null),this._indexBuffer&&(this._scene.getEngine()._releaseBuffer(this._indexBuffer),this._indexBuffer=null)}}class Zn{set opaqueSortCompareFn(e){this._opaqueSortCompareFn=e||Zn.PainterSortCompare,this._renderOpaque=this._renderOpaqueSorted}set alphaTestSortCompareFn(e){this._alphaTestSortCompareFn=e||Zn.PainterSortCompare,this._renderAlphaTest=this._renderAlphaTestSorted}set transparentSortCompareFn(e){this._transparentSortCompareFn=e||Zn.defaultTransparentSortCompare,this._renderTransparent=this._renderTransparentSorted}constructor(e,t,i=null,n=null,r=null){this.index=e,this._opaqueSubMeshes=new Zt(256),this._transparentSubMeshes=new Zt(256),this._alphaTestSubMeshes=new Zt(256),this._depthOnlySubMeshes=new Zt(256),this._particleSystems=new Zt(256),this._spriteManagers=new Zt(256),this._empty=!0,this._edgesRenderers=new Jt(16),this._scene=t,this.opaqueSortCompareFn=i,this.alphaTestSortCompareFn=n,this.transparentSortCompareFn=r}render(e,t,i,n){if(e)return void e(this._opaqueSubMeshes,this._alphaTestSubMeshes,this._transparentSubMeshes,this._depthOnlySubMeshes);const r=this._scene.getEngine();0!==this._depthOnlySubMeshes.length&&(r.setColorWrite(!1),this._renderAlphaTest(this._depthOnlySubMeshes),r.setColorWrite(!0)),0!==this._opaqueSubMeshes.length&&this._renderOpaque(this._opaqueSubMeshes),0!==this._alphaTestSubMeshes.length&&this._renderAlphaTest(this._alphaTestSubMeshes);const s=r.getStencilBuffer();if(r.setStencilBuffer(!1),t&&this._renderSprites(),i&&this._renderParticles(n),this.onBeforeTransparentRendering&&this.onBeforeTransparentRendering(),0!==this._transparentSubMeshes.length||this._scene.useOrderIndependentTransparency){if(r.setStencilBuffer(s),this._scene.useOrderIndependentTransparency){const e=this._scene.depthPeelingRenderer.render(this._transparentSubMeshes);e.length&&this._renderTransparent(e)}else this._renderTransparent(this._transparentSubMeshes);r.setAlphaMode(Ze.ALPHA_DISABLE)}if(r.setStencilBuffer(!1),this._edgesRenderers.length){for(let e=0;e<this._edgesRenderers.length;e++)this._edgesRenderers.data[e].render();r.setAlphaMode(Ze.ALPHA_DISABLE)}r.setStencilBuffer(s)}_renderOpaqueSorted(e){Zn._RenderSorted(e,this._opaqueSortCompareFn,this._scene.activeCamera,!1)}_renderAlphaTestSorted(e){Zn._RenderSorted(e,this._alphaTestSortCompareFn,this._scene.activeCamera,!1)}_renderTransparentSorted(e){Zn._RenderSorted(e,this._transparentSortCompareFn,this._scene.activeCamera,!0)}static _RenderSorted(e,t,i,n){let r,s=0;const a=i?i.globalPosition:Zn._ZeroVector;if(n)for(;s<e.length;s++)r=e.data[s],r._alphaIndex=r.getMesh().alphaIndex,r._distanceToCamera=B.Distance(r.getBoundingInfo().boundingSphere.centerWorld,a);const o=e.length===e.data.length?e.data:e.data.slice(0,e.length);t&&o.sort(t);const l=o[0].getMesh().getScene();for(s=0;s<o.length;s++)if(r=o[s],!l._activeMeshesFrozenButKeepClipping||r.isInFrustum(l._frustumPlanes)){if(n){const e=r.getMaterial();if(e&&e.needDepthPrePass){const t=e.getScene().getEngine();t.setColorWrite(!1),t.setAlphaMode(Ze.ALPHA_DISABLE),r.render(!1),t.setColorWrite(!0)}}r.render(n)}}static defaultTransparentSortCompare(e,t){return e._alphaIndex>t._alphaIndex?1:e._alphaIndex<t._alphaIndex?-1:Zn.backToFrontSortCompare(e,t)}static backToFrontSortCompare(e,t){return e._distanceToCamera<t._distanceToCamera?1:e._distanceToCamera>t._distanceToCamera?-1:0}static frontToBackSortCompare(e,t){return e._distanceToCamera<t._distanceToCamera?-1:e._distanceToCamera>t._distanceToCamera?1:0}static PainterSortCompare(e,t){const i=e.getMesh(),n=t.getMesh();return i.material&&n.material?i.material.uniqueId-n.material.uniqueId:i.uniqueId-n.uniqueId}prepare(){this._opaqueSubMeshes.reset(),this._transparentSubMeshes.reset(),this._alphaTestSubMeshes.reset(),this._depthOnlySubMeshes.reset(),this._particleSystems.reset(),this.prepareSprites(),this._edgesRenderers.reset(),this._empty=!0}prepareSprites(){this._spriteManagers.reset()}dispose(){this._opaqueSubMeshes.dispose(),this._transparentSubMeshes.dispose(),this._alphaTestSubMeshes.dispose(),this._depthOnlySubMeshes.dispose(),this._particleSystems.dispose(),this._spriteManagers.dispose(),this._edgesRenderers.dispose()}dispatch(e,t,i){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<this._particleSystems.length;i++){const n=this._particleSystems.data[i];if(0===(t&&t.layerMask&n.layerMask))continue;const r=n.emitter;r.position&&e&&-1===e.indexOf(r)||this._scene._activeParticles.addCount(n.render(),!1)}this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene)}_renderSprites(){if(!this._scene.spritesEnabled||0===this._spriteManagers.length)return;const e=this._scene.activeCamera;this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);for(let t=0;t<this._spriteManagers.length;t++){const i=this._spriteManagers.data[t];0!==(e&&e.layerMask&i.layerMask)&&i.render()}this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene)}}Zn._ZeroVector=B.Zero();class Jn{}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 Jn,this._maintainStateBetweenFrames=!1,this._scene=e;for(let e=$n.MIN_RENDERINGGROUPS;e<$n.MAX_RENDERINGGROUPS;e++)this._autoClearDepthStencil[e]={autoClear:!0,depth:!0,stencil:!0}}getRenderingGroup(e){const t=e||0;return this._prepareRenderingGroup(t),this._renderingGroups[t]}_clearDepthStencilBuffer(e=!0,t=!0){this._depthStencilBufferAlreadyCleaned||(this._scene.getEngine().clear(null,!1,e,t),this._depthStencilBufferAlreadyCleaned=!0)}render(e,t,i,n){const r=this._renderingGroupInfo;if(r.scene=this._scene,r.camera=this._scene.activeCamera,this._scene.spriteManagers&&n)for(let e=0;e<this._scene.spriteManagers.length;e++){const t=this._scene.spriteManagers[e];this.dispatchSprites(t)}for(let s=$n.MIN_RENDERINGGROUPS;s<$n.MAX_RENDERINGGROUPS;s++){this._depthStencilBufferAlreadyCleaned=s===$n.MIN_RENDERINGGROUPS;const a=this._renderingGroups[s];if(!a||a._empty)continue;const o=1<<s;if(r.renderingGroupId=s,this._scene.onBeforeRenderingGroupObservable.notifyObservers(r,o),$n.AUTOCLEAR){const e=this._useSceneAutoClearSetup?this._scene.getAutoClearDepthStencilSetup(s):this._autoClearDepthStencil[s];e&&e.autoClear&&this._clearDepthStencilBuffer(e.depth,e.stencil)}for(const e of this._scene._beforeRenderingGroupDrawStage)e.action(s);a.render(e,n,i,t);for(const e of this._scene._afterRenderingGroupDrawStage)e.action(s);this._scene.onAfterRenderingGroupObservable.notifyObservers(r,o)}}reset(){if(!this.maintainStateBetweenFrames)for(let e=$n.MIN_RENDERINGGROUPS;e<$n.MAX_RENDERINGGROUPS;e++){const t=this._renderingGroups[e];t&&t.prepare()}}resetSprites(){if(!this.maintainStateBetweenFrames)for(let e=$n.MIN_RENDERINGGROUPS;e<$n.MAX_RENDERINGGROUPS;e++){const t=this._renderingGroups[e];t&&t.prepareSprites()}}dispose(){this.freeRenderingGroups(),this._renderingGroups.length=0,this._renderingGroupInfo=null}freeRenderingGroups(){for(let e=$n.MIN_RENDERINGGROUPS;e<$n.MAX_RENDERINGGROUPS;e++){const t=this._renderingGroups[e];t&&t.dispose()}}_prepareRenderingGroup(e){void 0===this._renderingGroups[e]&&(this._renderingGroups[e]=new Zn(e,this._scene,this._customOpaqueSortCompareFn[e],this._customAlphaTestSortCompareFn[e],this._customTransparentSortCompareFn[e]))}dispatchSprites(e){this.maintainStateBetweenFrames&&e._wasDispatched||(e._wasDispatched=!0,this.getRenderingGroup(e.renderingGroupId).dispatchSprites(e))}dispatchParticles(e){this.maintainStateBetweenFrames&&e._wasDispatched||(e._wasDispatched=!0,this.getRenderingGroup(e.renderingGroupId).dispatchParticles(e))}dispatch(e,t,i){void 0===t&&(t=e.getMesh()),this.maintainStateBetweenFrames&&e._wasDispatched||(e._wasDispatched=!0,this.getRenderingGroup(t.renderingGroupId).dispatch(e,t,i))}setRenderingOrder(e,t=null,i=null,n=null){if(this._customOpaqueSortCompareFn[e]=t,this._customAlphaTestSortCompareFn[e]=i,this._customTransparentSortCompareFn[e]=n,this._renderingGroups[e]){const t=this._renderingGroups[e];t.opaqueSortCompareFn=this._customOpaqueSortCompareFn[e],t.alphaTestSortCompareFn=this._customAlphaTestSortCompareFn[e],t.transparentSortCompareFn=this._customTransparentSortCompareFn[e]}}setRenderingAutoClearDepthStencil(e,t,i=!0,n=!0){this._autoClearDepthStencil[e]={autoClear:t,depth:i,stencil:n}}getAutoClearDepthStencilSetup(e){return this._autoClearDepthStencil[e]}}$n.MAX_RENDERINGGROUPS=4,$n.MIN_RENDERINGGROUPS=0,$n.AUTOCLEAR=!0;class er{constructor(){this.hoverCursor="",this.actions=[],this.isRecursive=!1,this.disposeWhenUnowned=!0}static get HasTriggers(){for(const e in er.Triggers)if(Object.prototype.hasOwnProperty.call(er.Triggers,e))return!0;return!1}static get HasPickTriggers(){for(const e in er.Triggers)if(Object.prototype.hasOwnProperty.call(er.Triggers,e)){const t=parseInt(e);if(t>=Ze.ACTION_OnPickTrigger&&t<=Ze.ACTION_OnPickUpTrigger)return!0}return!1}static HasSpecificTrigger(e){for(const t in er.Triggers)if(Object.prototype.hasOwnProperty.call(er.Triggers,t)){if(parseInt(t)===e)return!0}return!1}}var tr,ir,nr,rr,sr,ar,or;er.Triggers={},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"}(tr||(tr={})),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"}(ir||(ir={})),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"}(nr||(nr={})),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"}(rr||(rr={})),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"}(sr||(sr={})),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"}(ar||(ar={})),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"}(or||(or={}));class lr{static CreateDeviceEvent(e,t,i,n,r,s,a){switch(e){case tr.Keyboard:return this._CreateKeyboardEvent(i,n,r,s);case tr.Mouse:if(i===ir.MouseWheelX||i===ir.MouseWheelY||i===ir.MouseWheelZ)return this._CreateWheelEvent(e,t,i,n,r,s);case tr.Touch:return this._CreatePointerEvent(e,t,i,n,r,s,a);default:throw`Unable to generate event for device ${tr[e]}`}}static _CreatePointerEvent(e,t,i,n,r,s,a){const o=this._CreateMouseEvent(e,t,i,n,r,s);e===tr.Mouse?(o.deviceType=tr.Mouse,o.pointerId=1,o.pointerType="mouse"):(o.deviceType=tr.Touch,o.pointerId=a??t,o.pointerType="touch");let l=0;return l+=r.pollInput(e,t,ir.LeftClick),l+=2*r.pollInput(e,t,ir.RightClick),l+=4*r.pollInput(e,t,ir.MiddleClick),o.buttons=l,i===ir.Move?o.type="pointermove":i>=ir.LeftClick&&i<=ir.RightClick&&(o.type=1===n?"pointerdown":"pointerup",o.button=i-2),o}static _CreateWheelEvent(e,t,i,n,r,s){const a=this._CreateMouseEvent(e,t,i,n,r,s);switch(a.pointerId=1,a.type="wheel",a.deltaMode=Bn.DOM_DELTA_PIXEL,a.deltaX=0,a.deltaY=0,a.deltaZ=0,i){case ir.MouseWheelX:a.deltaX=n;break;case ir.MouseWheelY:a.deltaY=n;break;case ir.MouseWheelZ:a.deltaZ=n}return a}static _CreateMouseEvent(e,t,i,n,r,s){const a=this._CreateEvent(s),o=r.pollInput(e,t,ir.Horizontal),l=r.pollInput(e,t,ir.Vertical);return s?(a.movementX=0,a.movementY=0,a.offsetX=a.movementX-s.getBoundingClientRect().x,a.offsetY=a.movementY-s.getBoundingClientRect().y):(a.movementX=r.pollInput(e,t,10),a.movementY=r.pollInput(e,t,11),a.offsetX=0,a.offsetY=0),this._CheckNonCharacterKeys(a,r),a.clientX=o,a.clientY=l,a.x=o,a.y=l,a.deviceType=e,a.deviceSlot=t,a.inputIndex=i,a}static _CreateKeyboardEvent(e,t,i,n){const r=this._CreateEvent(n);return this._CheckNonCharacterKeys(r,i),r.deviceType=tr.Keyboard,r.deviceSlot=0,r.inputIndex=e,r.type=1===t?"keydown":"keyup",r.key=String.fromCharCode(e),r.keyCode=e,r}static _CheckNonCharacterKeys(e,t){const i=t.isDeviceAvailable(tr.Keyboard),n=i&&1===t.pollInput(tr.Keyboard,0,Ze.INPUT_ALT_KEY),r=i&&1===t.pollInput(tr.Keyboard,0,Ze.INPUT_CTRL_KEY),s=i&&(1===t.pollInput(tr.Keyboard,0,Ze.INPUT_META_KEY1)||1===t.pollInput(tr.Keyboard,0,Ze.INPUT_META_KEY2)||1===t.pollInput(tr.Keyboard,0,Ze.INPUT_META_KEY3)),a=i&&1===t.pollInput(tr.Keyboard,0,Ze.INPUT_SHIFT_KEY);e.altKey=n,e.ctrlKey=r,e.metaKey=s,e.shiftKey=a}static _CreateEvent(e){const t={preventDefault:()=>{}};return t.target=e,t}}class cr{constructor(e,t,i){this._nativeInput=_native.DeviceInputSystem?new _native.DeviceInputSystem(e,t,((e,t,n,r)=>{const s=lr.CreateDeviceEvent(e,t,n,r,this);i(e,t,s)})):this._createDummyNativeInput()}pollInput(e,t,i){return this._nativeInput.pollInput(e,t,i)}isDeviceAvailable(e){return e===tr.Mouse||e===tr.Touch}dispose(){this._nativeInput.dispose()}_createDummyNativeInput(){return{pollInput:()=>0,isDeviceAvailable:()=>!1,dispose:()=>{}}}}const hr=Object.keys(ir).length/2;class dr{constructor(e,t,i,n){this._inputs=[],this._keyboardActive=!1,this._pointerActive=!1,this._usingSafari=Yt.IsSafari(),this._usingMacOS=le()&&/(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=le()&&navigator.userAgent&&-1!==navigator.userAgent.indexOf("Firefox"),this._isUsingChromium=le()&&navigator.userAgent&&-1!==navigator.userAgent.indexOf("Chrome"),this._maxTouchPoints=0,this._pointerInputClearObserver=null,this._gamepadConnectedEvent=e=>{},this._gamepadDisconnectedEvent=e=>{},this._eventPrefix=Yt.GetPointerPrefix(e),this._engine=e,this._onDeviceConnected=t,this._onDeviceDisconnected=i,this._onInputChanged=n,this._mouseId=this._isUsingFirefox?0:1,this._enableEvents(),this._usingMacOS&&(this._metaKeys=[]),this._engine._onEngineViewChanged||(this._engine._onEngineViewChanged=()=>{this._enableEvents()})}pollInput(e,t,i){const n=this._inputs[e][t];if(!n)throw`Unable to find device ${tr[e]}`;e>=tr.DualShock&&e<=tr.DualSense&&this._updateDevice(e,t,i);const r=n[i];if(void 0===r)throw`Unable to find input ${i} for device ${tr[e]} in slot ${t}`;return i===ir.Move&&Yt.Warn("Unable to provide information for PointerInput.Move. Try using PointerInput.Horizontal or PointerInput.Vertical for move data."),r}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<i.length;e++)i[e]=0}this._elementToAttachTo=e,this._elementToAttachTo.tabIndex=-1!==this._elementToAttachTo.tabIndex?this._elementToAttachTo.tabIndex:this._engine.canvasTabIndex,this._handleKeyActions(),this._handlePointerActions(),this._handleGamepadActions(),this._eventsAttached=!0,this._checkForConnectedDevices()}}_disableEvents(){this._elementToAttachTo&&(this._elementToAttachTo.removeEventListener("blur",this._keyboardBlurEvent),this._elementToAttachTo.removeEventListener("blur",this._pointerBlurEvent),this._elementToAttachTo.removeEventListener("keydown",this._keyboardDownEvent),this._elementToAttachTo.removeEventListener("keyup",this._keyboardUpEvent),this._elementToAttachTo.removeEventListener(this._eventPrefix+"move",this._pointerMoveEvent),this._elementToAttachTo.removeEventListener(this._eventPrefix+"down",this._pointerDownEvent),this._elementToAttachTo.removeEventListener(this._eventPrefix+"up",this._pointerUpEvent),this._elementToAttachTo.removeEventListener(this._eventPrefix+"cancel",this._pointerCancelEvent),this._elementToAttachTo.removeEventListener(this._wheelEventName,this._pointerWheelEvent),this._usingMacOS&&this._isUsingChromium&&this._elementToAttachTo.removeEventListener("lostpointercapture",this._pointerMacOSChromeOutEvent),window.removeEventListener("gamepadconnected",this._gamepadConnectedEvent),window.removeEventListener("gamepaddisconnected",this._gamepadDisconnectedEvent)),this._pointerInputClearObserver&&this._engine.onEndFrameObservable.remove(this._pointerInputClearObserver),this._eventsAttached=!1}_checkForConnectedDevices(){if(navigator.getGamepads){const e=navigator.getGamepads();for(const t of e)t&&this._addGamePad(t)}"function"==typeof matchMedia&&matchMedia("(pointer:fine)").matches&&this._addPointerDevice(tr.Mouse,0,0,0)}_addGamePad(e){const t=this._getGamepadDeviceType(e.id),i=e.index;this._gamepads=this._gamepads||new Array(e.index+1),this._registerDevice(t,i,e.buttons.length+e.axes.length),this._gamepads[i]=t}_addPointerDevice(e,t,i,n){this._pointerActive||(this._pointerActive=!0),this._registerDevice(e,t,hr);const r=this._inputs[e][t];r[0]=i,r[1]=n}_registerDevice(e,t,i){if(void 0===t)throw`Unable to register device ${tr[e]} to undefined slot.`;if(this._inputs[e]||(this._inputs[e]={}),!this._inputs[e][t]){const n=new Array(i);n.fill(0),this._inputs[e][t]=n,this._onDeviceConnected(e,t)}}_unregisterDevice(e,t){this._inputs[e][t]&&(delete this._inputs[e][t],this._onDeviceDisconnected(e,t))}_handleKeyActions(){this._keyboardDownEvent=e=>{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(tr.Keyboard,0,255));const t=this._inputs[tr.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(tr.Keyboard,0,i)}},this._keyboardUpEvent=e=>{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(tr.Keyboard,0,255));const t=this._inputs[tr.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=lr.CreateDeviceEvent(tr.Keyboard,0,e,0,this,this._elementToAttachTo);t[e]=0,this._onInputChanged(tr.Keyboard,0,i)}this._metaKeys.splice(0,this._metaKeys.length)}this._onInputChanged(tr.Keyboard,0,i)}},this._keyboardBlurEvent=()=>{if(this._keyboardActive){const e=this._inputs[tr.Keyboard][0];for(let t=0;t<e.length;t++)if(0!==e[t]){e[t]=0;const i=lr.CreateDeviceEvent(tr.Keyboard,0,t,0,this,this._elementToAttachTo);this._onInputChanged(tr.Keyboard,0,i)}this._usingMacOS&&this._metaKeys.splice(0,this._metaKeys.length)}},this._elementToAttachTo.addEventListener("keydown",this._keyboardDownEvent),this._elementToAttachTo.addEventListener("keyup",this._keyboardUpEvent),this._elementToAttachTo.addEventListener("blur",this._keyboardBlurEvent)}_handlePointerActions(){this._maxTouchPoints=le()&&navigator.maxTouchPoints||2,this._activeTouchIds||(this._activeTouchIds=new Array(this._maxTouchPoints));for(let e=0;e<this._maxTouchPoints;e++)this._activeTouchIds[e]=-1;this._pointerMoveEvent=e=>{const t=this._getPointerType(e);let i=t===tr.Mouse?0:this._activeTouchIds.indexOf(e.pointerId);if(t===tr.Touch&&-1===i){const n=this._activeTouchIds.indexOf(-1);if(!(n>=0))return void Yt.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`);i=n,this._activeTouchIds[n]=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 n=this._inputs[t][i];if(n){const r=e;r.inputIndex=ir.Move,n[ir.Horizontal]=e.clientX,n[ir.Vertical]=e.clientY,t===tr.Touch&&0===n[ir.LeftClick]&&(n[ir.LeftClick]=1),void 0===e.pointerId&&(e.pointerId=this._mouseId),this._onInputChanged(t,i,r),this._usingSafari||-1===e.button||(r.inputIndex=e.button+2,n[e.button+2]=n[e.button+2]?0:1,this._onInputChanged(t,i,r))}},this._pointerDownEvent=e=>{const t=this._getPointerType(e);let i=t===tr.Mouse?0:e.pointerId;if(t===tr.Touch){let t=this._activeTouchIds.indexOf(e.pointerId);if(-1===t&&(t=this._activeTouchIds.indexOf(-1)),!(t>=0))return void Yt.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===tr.Touch&&this._onDeviceConnected(t,i):this._addPointerDevice(t,i,e.clientX,e.clientY);const n=this._inputs[t][i];if(n){const r=n[ir.Horizontal],s=n[ir.Vertical];if(t===tr.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){}n[ir.Horizontal]=e.clientX,n[ir.Vertical]=e.clientY,n[e.button+2]=1;const a=e;a.inputIndex=e.button+2,this._onInputChanged(t,i,a),r===e.clientX&&s===e.clientY||(a.inputIndex=ir.Move,this._onInputChanged(t,i,a))}},this._pointerUpEvent=e=>{const t=this._getPointerType(e),i=t===tr.Mouse?0:this._activeTouchIds.indexOf(e.pointerId);if(t===tr.Touch){if(-1===i)return;this._activeTouchIds[i]=-1}const n=this._inputs[t]?.[i];if(n&&0!==n[e.button+2]){const r=n[ir.Horizontal],s=n[ir.Vertical];n[ir.Horizontal]=e.clientX,n[ir.Vertical]=e.clientY,n[e.button+2]=0;const a=e;void 0===e.pointerId&&(e.pointerId=this._mouseId),r===e.clientX&&s===e.clientY||(a.inputIndex=ir.Move,this._onInputChanged(t,i,a)),a.inputIndex=e.button+2,t===tr.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===tr.Touch&&this._onDeviceDisconnected(t,i)}},this._pointerCancelEvent=e=>{if("mouse"===e.pointerType){const e=this._inputs[tr.Mouse][0];this._mouseId>=0&&this._elementToAttachTo.hasPointerCapture?.(this._mouseId)&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let t=ir.LeftClick;t<=ir.BrowserForward;t++)if(1===e[t]){e[t]=0;const i=lr.CreateDeviceEvent(tr.Mouse,0,t,0,this,this._elementToAttachTo);this._onInputChanged(tr.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[tr.Touch][t][ir.LeftClick]=0;const i=lr.CreateDeviceEvent(tr.Touch,t,ir.LeftClick,0,this,this._elementToAttachTo,e.pointerId);this._onInputChanged(tr.Touch,t,i),this._activeTouchIds[t]=-1,this._onDeviceDisconnected(tr.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(tr.Mouse)){const e=this._inputs[tr.Mouse][0];this._mouseId>=0&&this._elementToAttachTo.hasPointerCapture?.(this._mouseId)&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let t=ir.LeftClick;t<=ir.BrowserForward;t++)if(1===e[t]){e[t]=0;const i=lr.CreateDeviceEvent(tr.Mouse,0,t,0,this,this._elementToAttachTo);this._onInputChanged(tr.Mouse,0,i)}}if(this.isDeviceAvailable(tr.Touch)){const e=this._inputs[tr.Touch];for(let t=0;t<this._activeTouchIds.length;t++){const i=this._activeTouchIds[t];if(this._elementToAttachTo.hasPointerCapture?.(i)&&this._elementToAttachTo.releasePointerCapture(i),-1!==i&&1===e[t]?.[ir.LeftClick]){e[t][ir.LeftClick]=0;const n=lr.CreateDeviceEvent(tr.Touch,t,ir.LeftClick,0,this,this._elementToAttachTo,i);this._onInputChanged(tr.Touch,t,n),this._activeTouchIds[t]=-1,this._onDeviceDisconnected(tr.Touch,t)}}}},this._pointerWheelEvent=e=>{const t=tr.Mouse;this._inputs[t]||(this._inputs[t]=[]),this._inputs[t][0]||(this._pointerActive=!0,this._registerDevice(t,0,hr));const i=this._inputs[t][0];if(i){i[ir.MouseWheelX]=e.deltaX||0,i[ir.MouseWheelY]=e.deltaY||e.wheelDelta||0,i[ir.MouseWheelZ]=e.deltaZ||0;const n=e;void 0===e.pointerId&&(e.pointerId=this._mouseId),0!==i[ir.MouseWheelX]&&(n.inputIndex=ir.MouseWheelX,this._onInputChanged(t,0,n)),0!==i[ir.MouseWheelY]&&(n.inputIndex=ir.MouseWheelY,this._onInputChanged(t,0,n)),0!==i[ir.MouseWheelZ]&&(n.inputIndex=ir.MouseWheelZ,this._onInputChanged(t,0,n))}},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(tr.Mouse)){const e=this._inputs[tr.Mouse][0];e[ir.MouseWheelX]=0,e[ir.MouseWheelY]=0,e[ir.MouseWheelZ]=0}}))}_handleGamepadActions(){this._gamepadConnectedEvent=e=>{this._addGamePad(e.gamepad)},this._gamepadDisconnectedEvent=e=>{if(this._gamepads){const t=this._getGamepadDeviceType(e.gamepad.id),i=e.gamepad.index;this._unregisterDevice(t,i),delete this._gamepads[i]}},window.addEventListener("gamepadconnected",this._gamepadConnectedEvent),window.addEventListener("gamepaddisconnected",this._gamepadDisconnectedEvent)}_updateDevice(e,t,i){const n=navigator.getGamepads()[t];if(n&&e===this._gamepads[t]){const r=this._inputs[e][t];i>=n.buttons.length?r[i]=n.axes[i-n.buttons.length].valueOf():r[i]=n.buttons[i].value}}_getGamepadDeviceType(e){return-1!==e.indexOf("054c")?-1!==e.indexOf("0ce6")?tr.DualSense:tr.DualShock:-1!==e.indexOf("Xbox One")||-1!==e.search("Xbox 360")||-1!==e.search("xinput")?tr.Xbox:-1!==e.indexOf("057e")?tr.Switch:tr.Generic}_getPointerType(e){let t=tr.Mouse;return("touch"===e.pointerType||"pen"===e.pointerType||e.touches)&&(t=tr.Touch),t}}class ur{constructor(e,t,i=0){this.deviceType=t,this.deviceSlot=i,this.onInputChangedObservable=new g,this._deviceInputSystem=e}getInput(e){return this._deviceInputSystem.pollInput(this.deviceType,this.deviceSlot,e)}}class fr{constructor(e){this._registeredManagers=new Array,this._refCount=0,this.registerManager=e=>{for(let t=0;t<this._devices.length;t++){const i=this._devices[t];for(const n in i){const i=+n;e._addDevice(new ur(this._deviceInputSystem,t,i))}}this._registeredManagers.push(e)},this.unregisterManager=e=>{const t=this._registeredManagers.indexOf(e);t>-1&&this._registeredManagers.splice(t,1)};const t=Object.keys(tr).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 n=new ur(this._deviceInputSystem,e,t);i._addDevice(n)}},n=(e,t)=>{this._devices[e]?.[t]&&delete this._devices[e][t];for(const i of this._registeredManagers)i._removeDevice(e,t)},r=(e,t,i)=>{if(i)for(const n of this._registeredManagers)n._onInputChanged(e,t,i)};"undefined"!=typeof _native?this._deviceInputSystem=new cr(i,n,r):this._deviceInputSystem=new dr(e,i,n,r)}dispose(){this._deviceInputSystem.dispose()}}class _r{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(tr).length/2;this._devices=new Array(t),this._firstDevice=new Array(t),this._engine=e,this._engine._deviceSourceManager||(this._engine._deviceSourceManager=new fr(e)),this._engine._deviceSourceManager._refCount++,this.onDeviceConnectedObservable=new g((e=>{for(const t of this._devices)if(t)for(const i of t)i&&this.onDeviceConnectedObservable.notifyObserver(e,i)})),this.onDeviceDisconnectedObservable=new g,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 tr.Keyboard:case tr.Mouse:this._firstDevice[e]=0;break;case tr.Touch:case tr.DualSense:case tr.DualShock:case tr.Xbox:case tr.Switch:case tr.Generic:{delete this._firstDevice[e];const t=this._devices[e];if(t)for(let i=0;i<t.length;i++)if(t[i]){this._firstDevice[e]=i;break}break}}}}class mr{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 pr{constructor(e){this._alreadyAttached=!1,this._meshPickProceed=!1,this._currentPickResult=null,this._previousPickResult=null,this._totalPointersPressed=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 U(0,0),this._previousStartingPointerPosition=new U(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||y.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 U(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,n=i.getEngine(),r=n.getInputElement();r&&(r.tabIndex=n.canvasTabIndex,i.doNotHandleCursors||(r.style.cursor=i.defaultCursor)),this._setCursorAndPointerOverMesh(e,t,i);for(const n of i._pointerMoveStage){e=e||this._pickMove(t);const i=!!e?.pickedMesh;e=n.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,i,r)}const s=t.inputIndex>=ir.MouseWheelX&&t.inputIndex<=ir.MouseWheelZ?cn.POINTERWHEEL:cn.POINTERMOVE;let a;i.onPointerMove&&(e=e||this._pickMove(t),i.onPointerMove(t,e,s)),e?(a=new un(s,t,e),this._setRayOnPointerInfo(e,t)):(a=new un(s,t,null,this),this._movePointerInfo=a),i.onPointerObservable.hasObservers()&&i.onPointerObservable.notifyObservers(a,s)}_setRayOnPointerInfo(e,t){const i=this._scene;e&&i._pickingAvailable&&(e.ray||(e.ray=i.createPickingRay(t.offsetX,t.offsetY,k.Identity(),i.activeCamera)))}_addCameraPointerObserver(e,t){return this._cameraObserverCount++,this._scene.onPointerObservable.add(e,t)}_removeCameraPointerObserver(e){return this._cameraObserverCount--,this._scene.onPointerObservable.remove(e)}_checkForPicking(){return!!(this._scene.onPointerObservable.observers.length>this._cameraObserverCount||this._scene.onPointerPick)}_checkPrePointerObservable(e,t,i){const n=this._scene,r=new dn(i,t,this._unTranslatedPointerX,this._unTranslatedPointerY);return e&&(r.originalPickingInfo=e,r.ray=e.ray,"xr-near"===t.pointerType&&e.originMesh&&(r.nearInteractionPickingInfo=e)),n.onPrePointerObservable.notifyObservers(r,i),!!r.skipOnPointerObservable}_pickMove(e){const t=this._scene,i=t.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,t.pointerMovePredicate,t.pointerMoveFastCheck,t.cameraToUseForPointers,t.pointerMoveTrianglePredicate);return this._setCursorAndPointerOverMesh(i,e,t),i}_setCursorAndPointerOverMesh(e,t,i){const n=i.getEngine().getInputElement();if(e?.pickedMesh){if(this.setPointerOverMesh(e.pickedMesh,t.pointerId,e,t),!i.doNotHandleCursors&&n&&this._pointerOverMesh){const e=this._pointerOverMesh._getActionManagerForTrigger();e&&e.hasPointerTriggers&&(n.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=ir.Move,this._checkPrePointerObservable(e,i,cn.POINTERMOVE)||this._processPointerMove(e,i)}simulatePointerDown(e,t){const i=new PointerEvent("pointerdown",t);i.inputIndex=i.button+2,this._checkPrePointerObservable(e,i,cn.POINTERDOWN)||this._processPointerDown(e,i)}_processPointerDown(e,t){const i=this._scene;if(e?.pickedMesh){this._pickedDownMesh=e.pickedMesh;const n=e.pickedMesh._getActionManagerForTrigger();if(n){if(n.hasPickTriggers)switch(n.processTrigger(Ze.ACTION_OnPickDownTrigger,jn.CreateNew(e.pickedMesh,t,e)),t.button){case 0:n.processTrigger(Ze.ACTION_OnLeftPickTrigger,jn.CreateNew(e.pickedMesh,t,e));break;case 1:n.processTrigger(Ze.ACTION_OnCenterPickTrigger,jn.CreateNew(e.pickedMesh,t,e));break;case 2:n.processTrigger(Ze.ACTION_OnRightPickTrigger,jn.CreateNew(e.pickedMesh,t,e))}n.hasSpecificTrigger(Ze.ACTION_OnLongPressTrigger)&&window.setTimeout((()=>{const e=i.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,(e=>e.isPickable&&e.isVisible&&e.isReady()&&e.actionManager&&e.actionManager.hasSpecificTrigger(Ze.ACTION_OnLongPressTrigger)&&e===this._pickedDownMesh),!1,i.cameraToUseForPointers);e?.pickedMesh&&n&&0!==this._totalPointersPressed&&Date.now()-this._startingPointerTime>pr.LongPressDelay&&!this._isPointerSwiping()&&(this._startingPointerTime=0,n.processTrigger(Ze.ACTION_OnLongPressTrigger,jn.CreateNew(e.pickedMesh,t)))}),pr.LongPressDelay)}}else for(const n of i._pointerDownStage)e=n.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,!1);let n;const r=cn.POINTERDOWN;e?(i.onPointerDown&&i.onPointerDown(t,e,r),n=new un(r,t,e),this._setRayOnPointerInfo(e,t)):n=new un(r,t,null,this),i.onPointerObservable.hasObservers()&&i.onPointerObservable.notifyObservers(n,r)}_isPointerSwiping(){return this._isSwiping}simulatePointerUp(e,t,i){const n=new PointerEvent("pointerup",t);n.inputIndex=ir.Move;const r=new mr;i?r.doubleClick=!0:r.singleClick=!0,this._checkPrePointerObservable(e,n,cn.POINTERUP)||this._processPointerUp(e,n,r)}_processPointerUp(e,t,i){const n=this._scene;if(e?.pickedMesh){if(this._pickedUpMesh=e.pickedMesh,this._pickedDownMesh===this._pickedUpMesh&&(n.onPointerPick&&n.onPointerPick(t,e),i.singleClick&&!i.ignore&&n.onPointerObservable.observers.length>this._cameraObserverCount)){const i=cn.POINTERPICK,r=new un(i,t,e);this._setRayOnPointerInfo(e,t),n.onPointerObservable.notifyObservers(r,i)}const r=e.pickedMesh._getActionManagerForTrigger();if(r&&!i.ignore){r.processTrigger(Ze.ACTION_OnPickUpTrigger,jn.CreateNew(e.pickedMesh,t,e)),!i.hasSwiped&&i.singleClick&&r.processTrigger(Ze.ACTION_OnPickTrigger,jn.CreateNew(e.pickedMesh,t,e));const n=e.pickedMesh._getActionManagerForTrigger(Ze.ACTION_OnDoublePickTrigger);i.doubleClick&&n&&n.processTrigger(Ze.ACTION_OnDoublePickTrigger,jn.CreateNew(e.pickedMesh,t,e))}}else if(!i.ignore)for(const r of n._pointerUpStage)e=r.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,i.doubleClick);if(this._pickedDownMesh&&this._pickedDownMesh!==this._pickedUpMesh){const e=this._pickedDownMesh._getActionManagerForTrigger(Ze.ACTION_OnPickOutTrigger);e&&e.processTrigger(Ze.ACTION_OnPickOutTrigger,jn.CreateNew(this._pickedDownMesh,t))}if(!i.ignore){const r=new un(cn.POINTERUP,t,e);if(this._setRayOnPointerInfo(e,t),n.onPointerObservable.notifyObservers(r,cn.POINTERUP),n.onPointerUp&&n.onPointerUp(t,e,cn.POINTERUP),!i.hasSwiped&&!this._skipPointerTap&&!this._isMultiTouchGesture){let r=0;if(i.singleClick?r=cn.POINTERTAP:i.doubleClick&&(r=cn.POINTERDOUBLETAP),r){const i=new un(r,t,e);n.onPointerObservable.hasObservers()&&n.onPointerObservable.hasSpecificMask(r)&&n.onPointerObservable.notifyObservers(i,r)}}}}isPointerCaptured(e=0){return this._pointerCaptures[e]}attachControl(e=!0,t=!0,i=!0,n=null){const r=this._scene,s=r.getEngine();n||(n=s.getInputElement()),this._alreadyAttached&&this.detachControl(),n&&(this._alreadyAttachedTo=n),this._deviceSourceManager=new _r(s),this._initActionManager=e=>{if(!this._meshPickProceed){const t=r.skipPointerUpPicking||0===r._registeredActions&&!this._checkForPicking()&&!r.onPointerUp?null:r.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,r.pointerUpPredicate,r.pointerUpFastCheck,r.cameraToUseForPointers,r.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>pr.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=cn.POINTERTAP,n=new un(i,t,this._currentPickResult);r.onPointerObservable.hasObservers()&&r.onPointerObservable.hasSpecificMask(i)&&r.onPointerObservable.notifyObservers(n,i),this._delayedClicks[e]=null}},this._initClickEvent=(e,t,i,n)=>{const r=new mr;this._currentPickResult=null;let s=null,a=e.hasSpecificMask(cn.POINTERPICK)||t.hasSpecificMask(cn.POINTERPICK)||e.hasSpecificMask(cn.POINTERTAP)||t.hasSpecificMask(cn.POINTERTAP)||e.hasSpecificMask(cn.POINTERDOUBLETAP)||t.hasSpecificMask(cn.POINTERDOUBLETAP);!a&&er&&(s=this._initActionManager(s,r),s&&(a=s.hasPickTriggers));let o=!1;if(a){const a=i.button;if(r.hasSwiped=this._isPointerSwiping(),!r.hasSwiped){let l=!pr.ExclusiveDoubleClickMode;if(l||(l=!e.hasSpecificMask(cn.POINTERDOUBLETAP)&&!t.hasSpecificMask(cn.POINTERDOUBLETAP),l&&!er.HasSpecificTrigger(Ze.ACTION_OnDoublePickTrigger)&&(s=this._initActionManager(s,r),s&&(l=!s.hasSpecificTrigger(Ze.ACTION_OnDoublePickTrigger)))),l)(Date.now()-this._previousStartingPointerTime>pr.DoubleClickDelay||a!==this._previousButtonPressed)&&(r.singleClick=!0,n(r,this._currentPickResult),o=!0);else{const e={evt:i,clickInfo:r,timeoutId:window.setTimeout(this._delayedSimpleClick.bind(this,a,r,n),pr.DoubleClickDelay)};this._delayedClicks[a]=e}let c=e.hasSpecificMask(cn.POINTERDOUBLETAP)||t.hasSpecificMask(cn.POINTERDOUBLETAP);!c&&er.HasSpecificTrigger(Ze.ACTION_OnDoublePickTrigger)&&(s=this._initActionManager(s,r),s&&(c=s.hasSpecificTrigger(Ze.ACTION_OnDoublePickTrigger))),c&&(a===this._previousButtonPressed&&Date.now()-this._previousStartingPointerTime<pr.DoubleClickDelay&&!this._doubleClickOccured?(r.hasSwiped||this._isPointerSwiping()?(this._doubleClickOccured=!1,this._previousStartingPointerTime=this._startingPointerTime,this._previousStartingPointerPosition.x=this._startingPointerPosition.x,this._previousStartingPointerPosition.y=this._startingPointerPosition.y,this._previousButtonPressed=a,pr.ExclusiveDoubleClickMode?(this._delayedClicks[a]&&(clearTimeout(this._delayedClicks[a]?.timeoutId),this._delayedClicks[a]=null),n(r,this._previousPickResult)):n(r,this._currentPickResult)):(this._previousStartingPointerTime=0,this._doubleClickOccured=!0,r.doubleClick=!0,r.ignore=!1,pr.ExclusiveDoubleClickMode&&this._delayedClicks[a]&&(clearTimeout(this._delayedClicks[a]?.timeoutId),this._delayedClicks[a]=null),n(r,this._currentPickResult)),o=!0):(this._doubleClickOccured=!1,this._previousStartingPointerTime=this._startingPointerTime,this._previousStartingPointerPosition.x=this._startingPointerPosition.x,this._previousStartingPointerPosition.y=this._startingPointerPosition.y,this._previousButtonPressed=a))}}o||n(r,this._currentPickResult)},this._onPointerMove=e=>{if(this._updatePointerPosition(e),this._isSwiping||-1===this._swipeButtonPressed||(this._isSwiping=Math.abs(this._startingPointerPosition.x-this._pointerX)>pr.DragMovementThreshold||Math.abs(this._startingPointerPosition.y-this._pointerY)>pr.DragMovementThreshold),s.isPointerLock&&s._verifyPointerLock(),this._checkPrePointerObservable(null,e,e.inputIndex>=ir.MouseWheelX&&e.inputIndex<=ir.MouseWheelZ?cn.POINTERWHEEL:cn.POINTERMOVE))return;if(!r.cameraToUseForPointers&&!r.activeCamera)return;if(r.skipPointerMovePicking)return void this._processPointerMove(new Ci,e);r.pointerMovePredicate||(r.pointerMovePredicate=e=>e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(e.enablePointerMoveEvents||r.constantlyUpdateMeshUnderPointer||null!==e._getActionManagerForTrigger())&&(!r.cameraToUseForPointers||!!(r.cameraToUseForPointers.layerMask&e.layerMask)));const t=r._registeredActions>0||r.constantlyUpdateMeshUnderPointer?this._pickMove(e):null;this._processPointerMove(t,e)},this._onPointerDown=e=>{if(this._totalPointersPressed++,this._pickedDownMesh=null,this._meshPickProceed=!1,pr.ExclusiveDoubleClickMode)for(let t=0;t<this._delayedClicks.length;t++)if(this._delayedClicks[t])if(e.button===t)clearTimeout(this._delayedClicks[t]?.timeoutId);else{const e=this._delayedClicks[t].clickInfo;this._doubleClickOccured=!1,e.singleClick=!0,e.ignore=!1;const i=this._delayedClicks[t].evt,n=cn.POINTERTAP,s=new un(n,i,this._currentPickResult);r.onPointerObservable.hasObservers()&&r.onPointerObservable.hasSpecificMask(n)&&r.onPointerObservable.notifyObservers(s,n),this._delayedClicks[t]=null}if(this._updatePointerPosition(e),-1===this._swipeButtonPressed&&(this._swipeButtonPressed=e.button),r.preventDefaultOnPointerDown&&n&&(e.preventDefault(),n.focus()),this._startingPointerPosition.x=this._pointerX,this._startingPointerPosition.y=this._pointerY,this._startingPointerTime=Date.now(),this._checkPrePointerObservable(null,e,cn.POINTERDOWN))return;if(!r.cameraToUseForPointers&&!r.activeCamera)return;let t;this._pointerCaptures[e.pointerId]=!0,r.pointerDownPredicate||(r.pointerDownPredicate=e=>e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(!r.cameraToUseForPointers||!!(r.cameraToUseForPointers.layerMask&e.layerMask))),this._pickedDownMesh=null,t=r.skipPointerDownPicking||0===r._registeredActions&&!this._checkForPicking()&&!r.onPointerDown?new Ci:r.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,r.pointerDownPredicate,r.pointerDownFastCheck,r.cameraToUseForPointers,r.pointerDownTrianglePredicate),this._processPointerDown(t,e)},this._onPointerUp=e=>{0!==this._totalPointersPressed&&(this._totalPointersPressed--,this._pickedUpMesh=null,this._meshPickProceed=!1,this._updatePointerPosition(e),r.preventDefaultOnPointerUp&&n&&(e.preventDefault(),n.focus()),this._initClickEvent(r.onPrePointerObservable,r.onPointerObservable,e,((t,i)=>{if(r.onPrePointerObservable.hasObservers()&&(this._skipPointerTap=!1,!t.ignore)){if(this._checkPrePointerObservable(null,e,cn.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&&r.onPrePointerObservable.hasSpecificMask(cn.POINTERTAP)&&this._checkPrePointerObservable(null,e,cn.POINTERTAP)&&(this._skipPointerTap=!0),t.doubleClick&&r.onPrePointerObservable.hasSpecificMask(cn.POINTERDOUBLETAP)&&this._checkPrePointerObservable(null,e,cn.POINTERDOUBLETAP)&&(this._skipPointerTap=!0))}this._pointerCaptures[e.pointerId]?(0===e.buttons&&(this._pointerCaptures[e.pointerId]=!1),(r.cameraToUseForPointers||r.activeCamera)&&(r.pointerUpPredicate||(r.pointerUpPredicate=e=>e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(!r.cameraToUseForPointers||!!(r.cameraToUseForPointers.layerMask&e.layerMask))),!this._meshPickProceed&&(er&&er.HasTriggers||this._checkForPicking()||r.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=Ln.KEYDOWN;if(r.onPreKeyboardObservable.hasObservers()){const i=new wn(t,e);if(r.onPreKeyboardObservable.notifyObservers(i,t),i.skipOnKeyboardObservable)return}if(r.onKeyboardObservable.hasObservers()){const i=new Fn(t,e);r.onKeyboardObservable.notifyObservers(i,t)}r.actionManager&&r.actionManager.processTrigger(Ze.ACTION_OnKeyDownTrigger,jn.CreateNewFromScene(r,e))},this._onKeyUp=e=>{const t=Ln.KEYUP;if(r.onPreKeyboardObservable.hasObservers()){const i=new wn(t,e);if(r.onPreKeyboardObservable.notifyObservers(i,t),i.skipOnKeyboardObservable)return}if(r.onKeyboardObservable.hasObservers()){const i=new Fn(t,e);r.onKeyboardObservable.notifyObservers(i,t)}r.actionManager&&r.actionManager.processTrigger(Ze.ACTION_OnKeyUpTrigger,jn.CreateNewFromScene(r,e))},this._deviceSourceManager.onDeviceConnectedObservable.add((n=>{n.deviceType===tr.Mouse?n.onInputChangedObservable.add((r=>{this._originMouseEvent=r,r.inputIndex===ir.LeftClick||r.inputIndex===ir.MiddleClick||r.inputIndex===ir.RightClick||r.inputIndex===ir.BrowserBack||r.inputIndex===ir.BrowserForward?t&&1===n.getInput(r.inputIndex)?this._onPointerDown(r):e&&0===n.getInput(r.inputIndex)&&this._onPointerUp(r):i&&(r.inputIndex===ir.Move?this._onPointerMove(r):r.inputIndex!==ir.MouseWheelX&&r.inputIndex!==ir.MouseWheelY&&r.inputIndex!==ir.MouseWheelZ||this._onPointerMove(r))})):n.deviceType===tr.Touch?n.onInputChangedObservable.add((r=>{r.inputIndex===ir.LeftClick&&(t&&1===n.getInput(r.inputIndex)?(this._onPointerDown(r),this._totalPointersPressed>1&&(this._isMultiTouchGesture=!0)):e&&0===n.getInput(r.inputIndex)&&(this._onPointerUp(r),0===this._totalPointersPressed&&(this._isMultiTouchGesture=!1))),i&&r.inputIndex===ir.Move&&this._onPointerMove(r)})):n.deviceType===tr.Keyboard&&n.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,n){if(!(this._meshUnderPointerId[t]!==e||e&&e._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting))return;const r=this._meshUnderPointerId[t];let s;r&&(s=r._getActionManagerForTrigger(Ze.ACTION_OnPointerOutTrigger),s&&s.processTrigger(Ze.ACTION_OnPointerOutTrigger,jn.CreateNew(r,n,{pointerId:t}))),e?(this._meshUnderPointerId[t]=e,this._pointerOverMesh=e,s=e._getActionManagerForTrigger(Ze.ACTION_OnPointerOverTrigger),s&&s.processTrigger(Ze.ACTION_OnPointerOverTrigger,jn.CreateNew(e,n,{pointerId:t,pickResult:i}))):(delete this._meshUnderPointerId[t],this._pointerOverMesh=null)}getPointerOverMesh(){return this.meshUnderPointer}_invalidateMesh(e){this._pointerOverMesh===e&&(this._pointerOverMesh=null),this._pickedDownMesh===e&&(this._pickedDownMesh=null),this._pickedUpMesh===e&&(this._pickedUpMesh=null);for(const t in this._meshUnderPointerId)this._meshUnderPointerId[t]===e&&delete this._meshUnderPointerId[t]}}pr.DragMovementThreshold=10,pr.LongPressDelay=500,pr.DoubleClickDelay=300,pr.ExclusiveDoubleClickMode=!1;class gr{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){gr.Enabled&&(this._current+=e,t&&this._fetchResult())}beginMonitoring(){gr.Enabled&&(this._startMonitoringTime=_e.Now)}endMonitoring(e=!0){if(!gr.Enabled)return;e&&this.fetchNewFrame();const t=_e.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=_e.Now;e-this._lastSecTime>1e3&&(this._lastSecAverage=this._lastSecAccumulated/this._lastSecValueCount,this._lastSecTime=e,this._lastSecAccumulated=0,this._lastSecValueCount=0)}}gr.Enabled=!0;class Er{static get UniqueId(){const e=this._UniqueIdCounter;return this._UniqueIdCounter++,e}}Er._UniqueIdCounter=1;class Tr{constructor(){this.pointerDownFastCheck=!1,this.pointerUpFastCheck=!1,this.pointerMoveFastCheck=!1,this.skipPointerMovePicking=!1,this.skipPointerDownPicking=!1,this.skipPointerUpPicking=!1}}var Ar,vr;!function(e){e[e.BackwardCompatible=0]="BackwardCompatible",e[e.Intermediate=1]="Intermediate",e[e.Aggressive=2]="Aggressive"}(Ar||(Ar={}));class Rr extends zn{static DefaultMaterialFactory(e){throw Y("StandardMaterial")}static CollisionCoordinatorFactory(){throw Y("DefaultCollisionCoordinator")}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture!==e&&(this._environmentTexture=e,this.markAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag))}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(Ze.MATERIAL_MiscDirtyFlag))}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(Ze.MATERIAL_MiscDirtyFlag))}get forcePointsCloud(){return this._forcePointsCloud}get animationPropertiesOverride(){return this._animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}set beforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),e&&(this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e))}set afterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),e&&(this._onAfterRenderObserver=this.onAfterRenderObservable.add(e))}set beforeCameraRender(e){this._onBeforeCameraRenderObserver&&this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._onBeforeCameraRenderObserver=this.onBeforeCameraRenderObservable.add(e)}set afterCameraRender(e){this._onAfterCameraRenderObserver&&this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver),this._onAfterCameraRenderObserver=this.onAfterCameraRenderObservable.add(e)}get pointerDownPredicate(){return this._pointerPickingConfiguration.pointerDownPredicate}set pointerDownPredicate(e){this._pointerPickingConfiguration.pointerDownPredicate=e}get pointerUpPredicate(){return this._pointerPickingConfiguration.pointerUpPredicate}set pointerUpPredicate(e){this._pointerPickingConfiguration.pointerUpPredicate=e}get pointerMovePredicate(){return this._pointerPickingConfiguration.pointerMovePredicate}set pointerMovePredicate(e){this._pointerPickingConfiguration.pointerMovePredicate=e}get pointerDownFastCheck(){return this._pointerPickingConfiguration.pointerDownFastCheck}set pointerDownFastCheck(e){this._pointerPickingConfiguration.pointerDownFastCheck=e}get pointerUpFastCheck(){return this._pointerPickingConfiguration.pointerUpFastCheck}set pointerUpFastCheck(e){this._pointerPickingConfiguration.pointerUpFastCheck=e}get pointerMoveFastCheck(){return this._pointerPickingConfiguration.pointerMoveFastCheck}set pointerMoveFastCheck(e){this._pointerPickingConfiguration.pointerMoveFastCheck=e}get skipPointerMovePicking(){return this._pointerPickingConfiguration.skipPointerMovePicking}set skipPointerMovePicking(e){this._pointerPickingConfiguration.skipPointerMovePicking=e}get skipPointerDownPicking(){return this._pointerPickingConfiguration.skipPointerDownPicking}set skipPointerDownPicking(e){this._pointerPickingConfiguration.skipPointerDownPicking=e}get skipPointerUpPicking(){return this._pointerPickingConfiguration.skipPointerUpPicking}set skipPointerUpPicking(e){this._pointerPickingConfiguration.skipPointerUpPicking=e}get unTranslatedPointer(){return this._inputManager.unTranslatedPointer}static get DragMovementThreshold(){return pr.DragMovementThreshold}static set DragMovementThreshold(e){pr.DragMovementThreshold=e}static get LongPressDelay(){return pr.LongPressDelay}static set LongPressDelay(e){pr.LongPressDelay=e}static get DoubleClickDelay(){return pr.DoubleClickDelay}static set DoubleClickDelay(e){pr.DoubleClickDelay=e}static get ExclusiveDoubleClickMode(){return pr.ExclusiveDoubleClickMode}static set ExclusiveDoubleClickMode(e){pr.ExclusiveDoubleClickMode=e}bindEyePosition(e,t="vEyePosition",i=!1){const n=this._forcedViewPosition?this._forcedViewPosition:this._mirroredCameraPosition?this._mirroredCameraPosition:this.activeCamera.globalPosition,r=this.useRightHandedSystem===(null!=this._mirroredCameraPosition);return H.Vector4[0].set(n.x,n.y,n.z,r?-1:1),e&&(i?e.setFloat3(t,H.Vector4[0].x,H.Vector4[0].y,H.Vector4[0].z):e.setVector4(t,H.Vector4[0])),H.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(Ze.MATERIAL_MiscDirtyFlag))}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(Ze.MATERIAL_MiscDirtyFlag))}get fogEnabled(){return this._fogEnabled}set fogMode(e){this._fogMode!==e&&(this._fogMode=e,this.markAllMaterialsAsDirty(Ze.MATERIAL_MiscDirtyFlag))}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(Ze.MATERIAL_LightDirtyFlag))}get shadowsEnabled(){return this._shadowsEnabled}set lightsEnabled(e){this._lightsEnabled!==e&&(this._lightsEnabled=e,this.markAllMaterialsAsDirty(Ze.MATERIAL_LightDirtyFlag))}get lightsEnabled(){return this._lightsEnabled}get activeCameras(){return this._activeCameras}set activeCameras(e){this._unObserveActiveCameras&&(this._unObserveActiveCameras(),this._unObserveActiveCameras=null),e&&(this._unObserveActiveCameras=I(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=Rr.DefaultMaterialFactory(this)),this._defaultMaterial}set defaultMaterial(e){this._defaultMaterial=e}set texturesEnabled(e){this._texturesEnabled!==e&&(this._texturesEnabled=e,this.markAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag))}get texturesEnabled(){return this._texturesEnabled}set skeletonsEnabled(e){this._skeletonsEnabled!==e&&(this._skeletonsEnabled=e,this.markAllMaterialsAsDirty(Ze.MATERIAL_AttributesDirtyFlag))}get skeletonsEnabled(){return this._skeletonsEnabled}get collisionCoordinator(){return this._collisionCoordinator||(this._collisionCoordinator=Rr.CollisionCoordinatorFactory(),this._collisionCoordinator.init(this)),this._collisionCoordinator}get renderingManager(){return this._renderingManager}get frustumPlanes(){return this._frustumPlanes}_registerTransientComponents(){if(this._transientComponents.length>0){for(const e of this._transientComponents)e.register();this._transientComponents.length=0}}_addComponent(e){this._components.push(e),this._transientComponents.push(e);const t=e;t.addFromContainer&&t.serialize&&this._serializableComponents.push(t)}_getComponent(e){for(const t of this._components)if(t.name===e)return t;return null}constructor(e,t){super(),this._inputManager=new pr(this),this.cameraToUseForPointers=null,this._isScene=!0,this._blockEntityCollection=!1,this.autoClear=!0,this.autoClearDepthAndStencil=!0,this.clearColor=new te(.2,.2,.3,1),this.ambientColor=new ee(0,0,0),this.environmentIntensity=1,this._performancePriority=0,this.onScenePerformancePriorityChangedObservable=new g,this._forceWireframe=!1,this._skipFrustumClipping=!1,this._forcePointsCloud=!1,this.animationsEnabled=!0,this._animationPropertiesOverride=null,this.useConstantAnimationDeltaTime=!1,this.constantlyUpdateMeshUnderPointer=!1,this.hoverCursor="pointer",this.defaultCursor="",this.doNotHandleCursors=!1,this.preventDefaultOnPointerDown=!0,this.preventDefaultOnPointerUp=!0,this.metadata=null,this.reservedDataStore=null,this.disableOfflineSupportExceptionRules=[],this.onDisposeObservable=new g,this._onDisposeObserver=null,this.onBeforeRenderObservable=new g,this._onBeforeRenderObserver=null,this.onAfterRenderObservable=new g,this.onAfterRenderCameraObservable=new g,this._onAfterRenderObserver=null,this.onBeforeAnimationsObservable=new g,this.onAfterAnimationsObservable=new g,this.onBeforeDrawPhaseObservable=new g,this.onAfterDrawPhaseObservable=new g,this.onReadyObservable=new g,this.onBeforeCameraRenderObservable=new g,this._onBeforeCameraRenderObserver=null,this.onAfterCameraRenderObservable=new g,this._onAfterCameraRenderObserver=null,this.onBeforeActiveMeshesEvaluationObservable=new g,this.onAfterActiveMeshesEvaluationObservable=new g,this.onBeforeParticlesRenderingObservable=new g,this.onAfterParticlesRenderingObservable=new g,this.onDataLoadedObservable=new g,this.onNewCameraAddedObservable=new g,this.onCameraRemovedObservable=new g,this.onNewLightAddedObservable=new g,this.onLightRemovedObservable=new g,this.onNewGeometryAddedObservable=new g,this.onGeometryRemovedObservable=new g,this.onNewTransformNodeAddedObservable=new g,this.onTransformNodeRemovedObservable=new g,this.onNewMeshAddedObservable=new g,this.onMeshRemovedObservable=new g,this.onNewSkeletonAddedObservable=new g,this.onSkeletonRemovedObservable=new g,this.onNewMaterialAddedObservable=new g,this.onNewMultiMaterialAddedObservable=new g,this.onMaterialRemovedObservable=new g,this.onMultiMaterialRemovedObservable=new g,this.onNewTextureAddedObservable=new g,this.onTextureRemovedObservable=new g,this.onBeforeRenderTargetsRenderObservable=new g,this.onAfterRenderTargetsRenderObservable=new g,this.onBeforeStepObservable=new g,this.onAfterStepObservable=new g,this.onActiveCameraChanged=new g,this.onActiveCamerasChanged=new g,this.onBeforeRenderingGroupObservable=new g,this.onAfterRenderingGroupObservable=new g,this.onMeshImportedObservable=new g,this.onAnimationFileImportedObservable=new g,this._registeredForLateAnimationBindings=new Jt(256),this._pointerPickingConfiguration=new Tr,this.onPrePointerObservable=new g,this.onPointerObservable=new g,this.onPreKeyboardObservable=new g,this.onKeyboardObservable=new g,this._useRightHandedSystem=!1,this._timeAccumulator=0,this._currentStepId=0,this._currentInternalStep=0,this._fogEnabled=!0,this._fogMode=Rr.FOGMODE_NONE,this.fogColor=new ee(.2,.2,.3),this.fogDensity=.1,this.fogStart=0,this.fogEnd=1e3,this.needsPreviousWorldMatrices=!1,this._shadowsEnabled=!0,this._lightsEnabled=!0,this._unObserveActiveCameras=null,this._texturesEnabled=!0,this.physicsEnabled=!0,this.particlesEnabled=!0,this.spritesEnabled=!0,this._skeletonsEnabled=!0,this.lensFlaresEnabled=!0,this.collisionsEnabled=!0,this.gravity=new B(0,-9.807,0),this.postProcessesEnabled=!0,this.renderTargetsEnabled=!0,this.dumpNextRenderTargets=!1,this.customRenderTargets=[],this.importedMeshesFiles=[],this.probesEnabled=!0,this._meshesForIntersections=new Jt(256),this.proceduralTexturesEnabled=!0,this._totalVertices=new gr,this._activeIndices=new gr,this._activeParticles=new gr,this._activeBones=new gr,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 Zt(256),this._processedMaterials=new Zt(256),this._renderTargets=new Jt(256),this._materialsRenderTargets=new Jt(256),this._activeParticleSystems=new Zt(256),this._activeSkeletons=new Jt(32),this._softwareSkinnedMeshes=new Jt(32),this._activeAnimatables=new Array,this._transformMatrix=k.Zero(),this.requireLightSorting=!1,this._components=[],this._serializableComponents=[],this._transientComponents=[],this._beforeCameraUpdateStage=tn.Create(),this._beforeClearStage=tn.Create(),this._beforeRenderTargetClearStage=tn.Create(),this._gatherRenderTargetsStage=tn.Create(),this._gatherActiveCameraRenderTargetsStage=tn.Create(),this._isReadyForMeshStage=tn.Create(),this._beforeEvaluateActiveMeshStage=tn.Create(),this._evaluateSubMeshStage=tn.Create(),this._preActiveMeshStage=tn.Create(),this._cameraDrawRenderTargetStage=tn.Create(),this._beforeCameraDrawStage=tn.Create(),this._beforeRenderTargetDrawStage=tn.Create(),this._beforeRenderingGroupDrawStage=tn.Create(),this._beforeRenderingMeshStage=tn.Create(),this._afterRenderingMeshStage=tn.Create(),this._afterRenderingGroupDrawStage=tn.Create(),this._afterCameraDrawStage=tn.Create(),this._afterCameraPostProcessStage=tn.Create(),this._afterRenderTargetDrawStage=tn.Create(),this._afterRenderTargetPostProcessStage=tn.Create(),this._afterRenderStage=tn.Create(),this._pointerMoveStage=tn.Create(),this._pointerDownStage=tn.Create(),this._pointerUpStage=tn.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||y.LastCreatedEngine,i.virtual?e._virtualScenes.push(this):(y._LastCreatedScene=this,e.scenes.push(this)),this._uid=null,this._renderingManager=new $n(this),Qn&&(this.postProcessManager=new Qn(this)),oe()&&this.attachControl(),this._createUbo(),qn&&(this._imageProcessingConfiguration=new qn),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(),n=i.currentRenderPassId;i.currentRenderPassId=this.activeCamera?.renderPassId??n;let r=!0;for(this._pendingData.length>0&&(r=!1),this.prePassRenderer?.update(),this.useOrderIndependentTransparency&&this.depthPeelingRenderer&&(r&&=this.depthPeelingRenderer.isReady()),e&&(this._processedMaterials.reset(),this._materialsRenderTargets.reset()),t=0;t<this.meshes.length;t++){const n=this.meshes[t];if(!n.subMeshes||0===n.subMeshes.length)continue;if(!n.isReady(!0)){r=!1;continue}const s=n.hasThinInstances||"InstancedMesh"===n.getClassName()||"InstancedLinesMesh"===n.getClassName()||i.getCaps().instancedArrays&&n.instances.length>0;for(const e of this._isReadyForMeshStage)e.action(n,s)||(r=!1);if(!e)continue;const a=n.material||this.defaultMaterial;if(a)if(a._storeEffectOnSubMeshes)for(const e of n.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 a.hasRenderTargetTextures&&null!=a.getRenderTargetTextures&&-1===this._processedMaterials.indexOf(a)&&(this._processedMaterials.push(a),this._materialsRenderTargets.concatWithNoDuplicate(a.getRenderTargetTextures()))}if(e)for(t=0;t<this._materialsRenderTargets.length;++t){this._materialsRenderTargets.data[t].isReadyForRendering()||(r=!1)}for(t=0;t<this.geometries.length;t++){this.geometries[t].delayLoadState===Ze.DELAYLOADSTATE_LOADING&&(r=!1)}if(this.activeCameras&&this.activeCameras.length>0)for(const e of this.activeCameras)e.isReady(!0)||(r=!1);else this.activeCamera&&(this.activeCamera.isReady(!0)||(r=!1));for(const e of this.particleSystems)e.isReady()||(r=!1);if(this.layers)for(const e of this.layers)e.isReady()||(r=!1);return i.areAllEffectsReady()||(r=!1),i.currentRenderPassId=n,r}resetCachedMaterial(){this._cachedMaterial=null,this._cachedEffect=null,this._cachedVisibility=null}registerBeforeRender(e){this.onBeforeRenderObservable.add(e)}unregisterBeforeRender(e){this.onBeforeRenderObservable.removeCallback(e)}registerAfterRender(e){this.onAfterRenderObservable.add(e)}unregisterAfterRender(e){this.onAfterRenderObservable.removeCallback(e)}_executeOnceBeforeRender(e){const t=()=>{e(),setTimeout((()=>{this.unregisterBeforeRender(t)}))};this.registerBeforeRender(t)}executeOnceBeforeRender(e,t){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=_e.Now}getViewMatrix(){return this._viewMatrix}getProjectionMatrix(){return this._projectionMatrix}getTransformMatrix(){return this._transformMatrix}setTransformMatrix(e,t,i,n){i||n||!this._multiviewSceneUbo||(this._multiviewSceneUbo.dispose(),this._multiviewSceneUbo=null),this._viewUpdateFlag===e.updateFlag&&this._projectionUpdateFlag===t.updateFlag||(this._viewUpdateFlag=e.updateFlag,this._projectionUpdateFlag=t.updateFlag,this._viewMatrix=e,this._projectionMatrix=t,this._viewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._frustumPlanes?ti.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=ti.GetPlanes(this._transformMatrix),this._multiviewSceneUbo&&this._multiviewSceneUbo.useUbo?this._updateMultiviewUbo(i,n):this._sceneUbo.useUbo&&(this._sceneUbo.updateMatrix("viewProjection",this._transformMatrix),this._sceneUbo.updateMatrix("view",this._viewMatrix),this._sceneUbo.updateMatrix("projection",this._projectionMatrix)))}getSceneUniformBuffer(){return this._multiviewSceneUbo?this._multiviewSceneUbo:this._sceneUbo}createSceneUniformBuffer(e){const t=new Pi(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 Er.UniqueId}addMesh(e,t=!1){this._blockEntityCollection||(this.meshes.push(e),e._resyncLightSources(),e.parent||e._addToSceneRootNodes(),this.onNewMeshAddedObservable.notifyObservers(e),t&&e.getChildMeshes().forEach((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.materials.length){if(t!==this.materials.length-1){const e=this.materials[this.materials.length-1];this.materials[t]=e,e._indexInSceneMaterialArray=t}e._indexInSceneMaterialArray=-1,this.materials.pop()}return this.onMaterialRemovedObservable.notifyObservers(e),t}removeActionManager(e){const t=this.actionManagers.indexOf(e);return-1!==t&&this.actionManagers.splice(t,1),t}removeTexture(e){const t=this.textures.indexOf(e);return-1!==t&&this.textures.splice(t,1),this.onTextureRemovedObservable.notifyObservers(e),t}addLight(e){if(!this._blockEntityCollection){this.lights.push(e),this.sortLightsByPriority(),e.parent||e._addToSceneRootNodes();for(const t of this.meshes)-1===t.lightSources.indexOf(e)&&(t.lightSources.push(e),t._resyncLightSources());this.onNewLightAddedObservable.notifyObservers(e)}}sortLightsByPriority(){this.requireLightSorting&&this.lights.sort(Xi.CompareLightsPriority)}addCamera(e){this._blockEntityCollection||(this.cameras.push(e),this.onNewCameraAddedObservable.notifyObservers(e),e.parent||e._addToSceneRootNodes())}addSkeleton(e){this._blockEntityCollection||(this.skeletons.push(e),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),this.onNewMultiMaterialAddedObservable.notifyObservers(e))}addMaterial(e){this._blockEntityCollection||e.getScene()===this&&-1!==e._indexInSceneMaterialArray||(e._indexInSceneMaterialArray=this.materials.length,this.materials.push(e),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;t<this.animationGroups.length;t++)if(this.animationGroups[t].name===e)return this.animationGroups[t];return null}_getMaterial(e,t){for(let e=0;e<this.materials.length;e++){const i=this.materials[e];if(t(i))return i}if(e)for(let e=0;e<this.multiMaterials.length;e++){const i=this.multiMaterials[e];if(t(i))return i}return null}getMaterialByUniqueID(e,t=!1){return this._getMaterial(t,(t=>t.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.textures.length;t++)if(this.textures[t].uniqueId===e)return this.textures[t];return null}getTextureByName(e){for(let t=0;t<this.textures.length;t++)if(this.textures[t].name===e)return this.textures[t];return null}getCameraById(e){for(let t=0;t<this.cameras.length;t++)if(this.cameras[t].id===e)return this.cameras[t];return null}getCameraByUniqueId(e){for(let t=0;t<this.cameras.length;t++)if(this.cameras[t].uniqueId===e)return this.cameras[t];return null}getCameraByName(e){for(let t=0;t<this.cameras.length;t++)if(this.cameras[t].name===e)return this.cameras[t];return null}getBoneById(e){for(let t=0;t<this.skeletons.length;t++){const i=this.skeletons[t];for(let t=0;t<i.bones.length;t++)if(i.bones[t].id===e)return i.bones[t]}return null}getBoneByName(e){for(let t=0;t<this.skeletons.length;t++){const i=this.skeletons[t];for(let t=0;t<i.bones.length;t++)if(i.bones[t].name===e)return i.bones[t]}return null}getLightByName(e){for(let t=0;t<this.lights.length;t++)if(this.lights[t].name===e)return this.lights[t];return null}getLightById(e){for(let t=0;t<this.lights.length;t++)if(this.lights[t].id===e)return this.lights[t];return null}getLightByUniqueId(e){for(let t=0;t<this.lights.length;t++)if(this.lights[t].uniqueId===e)return this.lights[t];return null}getParticleSystemById(e){for(let t=0;t<this.particleSystems.length;t++)if(this.particleSystems[t].id===e)return this.particleSystems[t];return null}getGeometryById(e){for(let t=0;t<this.geometries.length;t++)if(this.geometries[t].id===e)return this.geometries[t];return null}_getGeometryByUniqueId(e){if(this._geometriesByUniqueId){const t=this._geometriesByUniqueId[e];if(void 0!==t)return this.geometries[t]}else for(let t=0;t<this.geometries.length;t++)if(this.geometries[t].uniqueId===e)return this.geometries[t];return null}pushGeometry(e,t){return!(!t&&this._getGeometryByUniqueId(e.uniqueId))&&(this.addGeometry(e),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<this.meshes.length;t++)if(this.meshes[t].id===e)return this.meshes[t];return null}getMeshesById(e){return this.meshes.filter((function(t){return t.id===e}))}getTransformNodeById(e){for(let t=0;t<this.transformNodes.length;t++)if(this.transformNodes[t].id===e)return this.transformNodes[t];return null}getTransformNodeByUniqueId(e){for(let t=0;t<this.transformNodes.length;t++)if(this.transformNodes[t].uniqueId===e)return this.transformNodes[t];return null}getTransformNodesById(e){return this.transformNodes.filter((function(t){return t.id===e}))}getMeshByUniqueId(e){for(let t=0;t<this.meshes.length;t++)if(this.meshes[t].uniqueId===e)return this.meshes[t];return null}getLastMeshById(e){for(let t=this.meshes.length-1;t>=0;t--)if(this.meshes[t].id===e)return this.meshes[t];return null}getLastTransformNodeById(e){for(let t=this.transformNodes.length-1;t>=0;t--)if(this.transformNodes[t].id===e)return this.transformNodes[t];return null}getLastEntryById(e){let t;for(t=this.meshes.length-1;t>=0;t--)if(this.meshes[t].id===e)return this.meshes[t];for(t=this.transformNodes.length-1;t>=0;t--)if(this.transformNodes[t].id===e)return this.transformNodes[t];for(t=this.cameras.length-1;t>=0;t--)if(this.cameras[t].id===e)return this.cameras[t];for(t=this.lights.length-1;t>=0;t--)if(this.lights[t].id===e)return this.lights[t];return null}getNodeById(e){const t=this.getMeshById(e);if(t)return t;const i=this.getTransformNodeById(e);if(i)return i;const n=this.getLightById(e);if(n)return n;const r=this.getCameraById(e);if(r)return r;const s=this.getBoneById(e);return s||null}getNodeByName(e){const t=this.getMeshByName(e);if(t)return t;const i=this.getTransformNodeByName(e);if(i)return i;const n=this.getLightByName(e);if(n)return n;const r=this.getCameraByName(e);if(r)return r;const s=this.getBoneByName(e);return s||null}getMeshByName(e){for(let t=0;t<this.meshes.length;t++)if(this.meshes[t].name===e)return this.meshes[t];return null}getTransformNodeByName(e){for(let t=0;t<this.transformNodes.length;t++)if(this.transformNodes[t].name===e)return this.transformNodes[t];return null}getLastSkeletonById(e){for(let t=this.skeletons.length-1;t>=0;t--)if(this.skeletons[t].id===e)return this.skeletons[t];return null}getSkeletonByUniqueId(e){for(let t=0;t<this.skeletons.length;t++)if(this.skeletons[t].uniqueId===e)return this.skeletons[t];return null}getSkeletonById(e){for(let t=0;t<this.skeletons.length;t++)if(this.skeletons[t].id===e)return this.skeletons[t];return null}getSkeletonByName(e){for(let t=0;t<this.skeletons.length;t++)if(this.skeletons[t].name===e)return this.skeletons[t];return null}getMorphTargetManagerById(e){for(let t=0;t<this.morphTargetManagers.length;t++)if(this.morphTargetManagers[t].uniqueId===e)return this.morphTargetManagers[t];return null}getMorphTargetById(e){for(let t=0;t<this.morphTargetManagers.length;++t){const i=this.morphTargetManagers[t];for(let t=0;t<i.numTargets;++t){const n=i.getTarget(t);if(n.id===e)return n}}return null}getMorphTargetByName(e){for(let t=0;t<this.morphTargetManagers.length;++t){const i=this.morphTargetManagers[t];for(let t=0;t<i.numTargets;++t){const n=i.getTarget(t);if(n.name===e)return n}}return null}getPostProcessByName(e){for(let t=0;t<this.postProcesses.length;++t){const i=this.postProcesses[t];if(i.name===e)return i}return null}isActiveMesh(e){return-1!==this._activeMeshes.indexOf(e)}get uid(){return this._uid||(this._uid=Yt.RandomId()),this._uid}addExternalData(e,t){return this._externalData||(this._externalData=new Wn),this._externalData.add(e,t)}getExternalData(e){return this._externalData?this._externalData.get(e):null}getOrAddExternalDataWithFactory(e,t){return this._externalData||(this._externalData=new Wn),this._externalData.getOrAddWithFactory(e,t)}removeExternalData(e){return this._externalData.remove(e)}_evaluateSubMesh(e,t,i,n){if(n||e.isInFrustum(this._frustumPlanes)){for(const i of this._evaluateSubMeshStage)i.action(t,e);const i=e.getMaterial();null!=i&&(i.hasRenderTargetTextures&&null!=i.getRenderTargetTextures&&-1===this._processedMaterials.indexOf(i)&&(this._processedMaterials.push(i),this._materialsRenderTargets.concatWithNoDuplicate(i.getRenderTargetTextures())),this._renderingManager.dispatch(e,t,i))}}freeProcessedMaterials(){this._processedMaterials.dispose()}get blockfreeActiveMeshesAndRenderingGroups(){return this._preventFreeActiveMeshesAndRenderingGroups}set blockfreeActiveMeshesAndRenderingGroups(e){this._preventFreeActiveMeshesAndRenderingGroups!==e&&(e&&(this.freeActiveMeshes(),this.freeRenderingGroups()),this._preventFreeActiveMeshesAndRenderingGroups=e)}freeActiveMeshes(){if(!this.blockfreeActiveMeshesAndRenderingGroups&&(this._activeMeshes.dispose(),this.activeCamera&&this.activeCamera._activeMeshes&&this.activeCamera._activeMeshes.dispose(),this.activeCameras))for(let e=0;e<this.activeCameras.length;e++){const t=this.activeCameras[e];t&&t._activeMeshes&&t._activeMeshes.dispose()}}freeRenderingGroups(){if(!this.blockfreeActiveMeshesAndRenderingGroups&&(this._renderingManager&&this._renderingManager.freeRenderingGroups(),this.textures))for(let e=0;e<this.textures.length;e++){const t=this.textures[e];t&&t.renderList&&t.freeRenderingGroups()}}_isInIntermediateRendering(){return this._intermediateRendering}freezeActiveMeshes(e=!1,t,i,n=!0,r=!1){return this.executeWhenReady((()=>{if(this.activeCamera){if(this._frustumPlanes||this.updateTransformMatrix(),this._evaluateActiveMeshes(),this._activeMeshesFrozen=!0,this._activeMeshesFrozenButKeepClipping=r,this._skipEvaluateActiveMeshesCompletely=e,n)for(let e=0;e<this._activeMeshes.length;e++)this._activeMeshes.data[e]._freeze();t&&t()}else i&&i("No active camera found")})),this}unfreezeActiveMeshes(){for(let e=0;e<this.meshes.length;e++){const t=this.meshes[e];t._internalAbstractMeshDataInfo&&(t._internalAbstractMeshDataInfo._isActive=!1)}for(let e=0;e<this._activeMeshes.length;e++)this._activeMeshes.data[e]._unFreeze();return this._activeMeshesFrozen=!1,this}_executeActiveContainerCleanup(e){(!this._engine.snapshotRendering||this._engine.snapshotRenderingMode!==Ze.SNAPSHOTRENDERING_FAST)&&this._activeMeshesFrozen&&this._activeMeshes.length||this.onBeforeRenderObservable.addOnce((()=>e.dispose()))}_evaluateActiveMeshes(){if(this._engine.snapshotRendering&&this._engine.snapshotRenderingMode===Ze.SNAPSHOTRENDERING_FAST)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;t<e;t++){this._activeMeshes.data[t].computeWorldMatrix()}}if(this._activeParticleSystems){const e=this._activeParticleSystems.length;for(let t=0;t<e;t++)this._activeParticleSystems.data[t].animate()}return void this._renderingManager.resetSprites()}if(!this.activeCamera)return;this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this),this.activeCamera._activeMeshes.reset(),this._activeMeshes.reset(),this._renderingManager.reset(),this._processedMaterials.reset(),this._activeParticleSystems.reset(),this._activeSkeletons.reset(),this._softwareSkinnedMeshes.reset(),this._materialsRenderTargets.reset();for(const e of this._beforeEvaluateActiveMeshStage)e.action();const e=this.getActiveMeshCandidates(),t=e.length;for(let i=0;i<t;i++){const t=e.data[i];if(t._internalAbstractMeshDataInfo._currentLODIsUpToDate=!1,t.isBlocked)continue;if(this._totalVertices.addCount(t.getTotalVertices(),!1),!t.isReady()||!t.isEnabled()||t.scaling.hasAZeroComponent)continue;t.computeWorldMatrix(),t.actionManager&&t.actionManager.hasSpecificTriggers2(Ze.ACTION_OnIntersectionEnterTrigger,Ze.ACTION_OnIntersectionExitTrigger)&&this._meshesForIntersections.pushNoDuplicate(t);let n=this.customLODSelector?this.customLODSelector(t,this.activeCamera):t.getLOD(this.activeCamera);if(t._internalAbstractMeshDataInfo._currentLOD=n,t._internalAbstractMeshDataInfo._currentLODIsUpToDate=!0,null!=n&&(n!==t&&0!==n.billboardMode&&n.computeWorldMatrix(),t._preActivate(),t.isVisible&&t.visibility>0&&t.layerMask&this.activeCamera.layerMask&&(this._skipFrustumClipping||t.alwaysSelectAsActiveMesh||t.isInFrustum(this._frustumPlanes)))){this._activeMeshes.push(t),this.activeCamera._activeMeshes.push(t),n!==t&&n._activate(this._renderId,!1);for(const e of this._preActiveMeshStage)e.action(t);t._activate(this._renderId,!1)&&(t.isAnInstance?t._internalAbstractMeshDataInfo._actAsRegularMesh&&(n=t):n._internalAbstractMeshDataInfo._onlyForInstances=!1,n._internalAbstractMeshDataInfo._isActive=!0,this._activeMesh(t,n)),t._postActivate()}}if(this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this),this.particlesEnabled){this.onBeforeParticlesRenderingObservable.notifyObservers(this);for(let e=0;e<this.particleSystems.length;e++){const t=this.particleSystems[e];if(!t.isStarted()||!t.emitter)continue;const i=t.emitter;i.position&&!i.isEnabled()||(this._activeParticleSystems.push(t),t.animate(),this._renderingManager.dispatchParticles(t))}this.onAfterParticlesRenderingObservable.notifyObservers(this)}}_activeMesh(e,t){this._skeletonsEnabled&&null!==t.skeleton&&void 0!==t.skeleton&&(this._activeSkeletons.pushNoDuplicate(t.skeleton)&&(t.skeleton.prepare(),this._activeBones.addCount(t.skeleton.bones.length,!1)),t.computeBonesUsingShaders||this._softwareSkinnedMeshes.pushNoDuplicate(t));let i=e.hasInstances||e.isAnInstance||this.dispatchAllSubMeshesOfActiveMeshes||this._skipFrustumClipping||t.alwaysSelectAsActiveMesh;if(t&&t.subMeshes&&t.subMeshes.length>0){const n=this.getActiveSubMeshCandidates(t),r=n.length;i=i||1===r;for(let s=0;s<r;s++){const r=n.data[s];this._evaluateSubMesh(r,t,e,i)}}}updateTransformMatrix(e){const t=this.activeCamera;if(t)if(t._renderingMultiview){const i=t._rigCameras[0],n=t._rigCameras[1];this.setTransformMatrix(i.getViewMatrix(),i.getProjectionMatrix(e),n.getViewMatrix(),n.getProjectionMatrix(e))}else this.setTransformMatrix(t.getViewMatrix(),t.getProjectionMatrix(e))}_bindFrameBuffer(e,t=!0){e&&e._multiviewTexture?e._multiviewTexture._bindFrameBuffer():e&&e.outputRenderTarget?e.outputRenderTarget._bindFrameBuffer():this._engine._currentFrameBufferIsDefaultFrameBuffer()||this._engine.restoreDefaultFramebuffer(),t&&this._clearFrameBuffer(e)}_clearFrameBuffer(e){if(e&&e._multiviewTexture);else if(e&&e.outputRenderTarget&&!e._renderingMultiview){const t=e.outputRenderTarget;t.onClearObservable.hasObservers()?t.onClearObservable.notifyObservers(this._engine):t.skipInitialClear||e.isRightCamera||(this.autoClear&&this._engine.clear(t.clearColor||this.clearColor,!t._cleared,!0,!0),t._cleared=!0)}else this._defaultFrameBufferCleared?this._engine.clear(null,!1,!0,!0):(this._defaultFrameBufferCleared=!0,this._clear())}_renderForCamera(e,t,i=!0){if(e&&e._skipRendering)return;const n=this._engine;if(this._activeCamera=e,!this.activeCamera)throw new Error("Active camera not set");if(n.setViewport(this.activeCamera.viewport),this.resetCachedMaterial(),this._renderId++,!this.prePass&&i){let t=!0;e._renderingMultiview&&e.outputRenderTarget&&(t=e.outputRenderTarget.skipInitialClear,this.autoClear&&(this._defaultFrameBufferCleared=!1,e.outputRenderTarget.skipInitialClear=!1)),this._bindFrameBuffer(this._activeCamera),e._renderingMultiview&&e.outputRenderTarget&&(e.outputRenderTarget.skipInitialClear=t)}this.updateTransformMatrix(),this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera),this._evaluateActiveMeshes();for(let e=0;e<this._softwareSkinnedMeshes.length;e++){const t=this._softwareSkinnedMeshes.data[e];t.applySkeleton(t.skeleton)}this.onBeforeRenderTargetsRenderObservable.notifyObservers(this),this._renderTargets.concatWithNoDuplicate(this._materialsRenderTargets),e.customRenderTargets&&e.customRenderTargets.length>0&&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 r=!1;if(this.renderTargetsEnabled){if(this._intermediateRendering=!0,this._renderTargets.length>0){Yt.StartPerformanceCounter("Render targets",this._renderTargets.length>0);for(let e=0;e<this._renderTargets.length;e++){const t=this._renderTargets.data[e];if(t._shouldRender()){this._renderId++;const e=t.activeCamera&&t.activeCamera!==this.activeCamera;t.render(e,this.dumpNextRenderTargets),r=!0}}Yt.EndPerformanceCounter("Render targets",this._renderTargets.length>0),this._renderId++}for(const e of this._cameraDrawRenderTargetStage)r=e.action(this.activeCamera)||r;this._intermediateRendering=!1}this._engine.currentRenderPassId=e.outputRenderTarget?.renderPassId??e.renderPassId??Ze.RENDERPASS_MAIN,r&&!this.prePass&&(this._bindFrameBuffer(this._activeCamera,!1),this.updateTransformMatrix()),this.onAfterRenderTargetsRenderObservable.notifyObservers(this),!this.postProcessManager||e._multiviewTexture||this.prePass||this.postProcessManager._prepareFrame();for(const e of this._beforeCameraDrawStage)e.action(this.activeCamera);this.onBeforeDrawPhaseObservable.notifyObservers(this),n.snapshotRendering&&n.snapshotRenderingMode===Ze.SNAPSHOTRENDERING_FAST&&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(e.cameraRigMode===Ze.RIG_MODE_NONE||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<e._rigCameras.length;t++)this._renderForCamera(e._rigCameras[t],e)}this._activeCamera=e,this.updateTransformMatrix(),this.onAfterRenderCameraObservable.notifyObservers(e)}_checkIntersections(){for(let e=0;e<this._meshesForIntersections.length;e++){const t=this._meshesForIntersections.data[e];if(t.actionManager)for(let e=0;t.actionManager&&e<t.actionManager.actions.length;e++){const i=t.actionManager.actions[e];if(i.trigger===Ze.ACTION_OnIntersectionEnterTrigger||i.trigger===Ze.ACTION_OnIntersectionExitTrigger){const e=i.getTriggerParameter(),n=e.mesh?e.mesh:e,r=n.intersectsMesh(t,e.usePreciseIntersection),s=t._intersectionsInProgress.indexOf(n);r&&-1===s?i.trigger===Ze.ACTION_OnIntersectionEnterTrigger?(i._executeCurrent(jn.CreateNew(t,void 0,n)),t._intersectionsInProgress.push(n)):i.trigger===Ze.ACTION_OnIntersectionExitTrigger&&t._intersectionsInProgress.push(n):!r&&s>-1&&(i.trigger===Ze.ACTION_OnIntersectionExitTrigger&&i._executeCurrent(jn.CreateNew(t,void 0,n)),t.actionManager.hasSpecificTrigger(Ze.ACTION_OnIntersectionExitTrigger,(e=>{const t=e.mesh?e.mesh:e;return n===t}))&&i.trigger!==Ze.ACTION_OnIntersectionExitTrigger||t._intersectionsInProgress.splice(s,1))}}}}_advancePhysicsEngineStep(e){}_animate(e){}animate(){if(this._engine.isDeterministicLockStep()){let e=Math.max(Rr.MinDeltaTime,Math.min(this._engine.getDeltaTime(),Rr.MaxDeltaTime))+this._timeAccumulator;const t=this._engine.getTimeStep(),i=1e3/t/1e3;let n=0;const r=this._engine.getLockstepMaxSteps();let s=Math.floor(e/t);for(s=Math.min(s,r);e>0&&n<s;)this.onBeforeStepObservable.notifyObservers(this),this._animationRatio=t*i,this._animate(t),this.onAfterAnimationsObservable.notifyObservers(this),this.physicsEnabled&&this._advancePhysicsEngineStep(t),this.onAfterStepObservable.notifyObservers(this),this._currentStepId++,n++,e-=t;this._timeAccumulator=e<0?0:e}else{const e=this.useConstantAnimationDeltaTime?16:Math.max(Rr.MinDeltaTime,Math.min(this._engine.getDeltaTime(),Rr.MaxDeltaTime));this._animationRatio=.06*e,this._animate(),this.onAfterAnimationsObservable.notifyObservers(this),this.physicsEnabled&&this._advancePhysicsEngineStep(e)}}_clear(){(this.autoClearDepthAndStencil||this.autoClear)&&this._engine.clear(this.clearColor,this.autoClear||this.forceWireframe||this.forcePointsCloud,this.autoClearDepthAndStencil,this.autoClearDepthAndStencil)}_checkCameraRenderTarget(e){if(e?.outputRenderTarget&&!e?.isRigCamera&&(e.outputRenderTarget._cleared=!1),e?.rigCameras?.length)for(let t=0;t<e.rigCameras.length;++t){const i=e.rigCameras[t].outputRenderTarget;i&&(i._cleared=!1)}}resetDrawCache(e){if(this.meshes)for(const t of this.meshes)t.resetDrawCache(e)}render(e=!0,t=!1){if(this.isDisposed)return;this.onReadyObservable.hasObservers()&&null===this._executeWhenReadyTimeoutId&&this._checkIsReady(),this._frameId++,this._defaultFrameBufferCleared=!1,this._checkCameraRenderTarget(this.activeCamera),this.activeCameras?.length&&this.activeCameras.forEach(this._checkCameraRenderTarget),this._registerTransientComponents(),this._activeParticles.fetchNewFrame(),this._totalVertices.fetchNewFrame(),this._activeIndices.fetchNewFrame(),this._activeBones.fetchNewFrame(),this._meshesForIntersections.reset(),this.resetCachedMaterial(),this.onBeforeAnimationsObservable.notifyObservers(this),this.actionManager&&this.actionManager.processTrigger(Ze.ACTION_OnEveryFrameTrigger),t||this.animate();for(const e of this._beforeCameraUpdateStage)e.action();if(e)if(this.activeCameras&&this.activeCameras.length>0)for(let e=0;e<this.activeCameras.length;e++){const t=this.activeCameras[e];if(t.update(),t.cameraRigMode!==Ze.RIG_MODE_NONE)for(let e=0;e<t._rigCameras.length;e++)t._rigCameras[e].update()}else if(this.activeCamera&&(this.activeCamera.update(),this.activeCamera.cameraRigMode!==Ze.RIG_MODE_NONE))for(let e=0;e<this.activeCamera._rigCameras.length;e++)this.activeCamera._rigCameras[e].update();this.onBeforeRenderObservable.notifyObservers(this);const i=this.getEngine();this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);const n=this.activeCameras?.length?this.activeCameras[0]:this.activeCamera;if(this.renderTargetsEnabled){Yt.StartPerformanceCounter("Custom render targets",this.customRenderTargets.length>0),this._intermediateRendering=!0;for(let e=0;e<this.customRenderTargets.length;e++){const t=this.customRenderTargets[e];if(t._shouldRender()){if(this._renderId++,this.activeCamera=t.activeCamera||this.activeCamera,!this.activeCamera)throw new Error("Active camera not set");i.setViewport(this.activeCamera.viewport),this.updateTransformMatrix(),t.render(n!==this.activeCamera,this.dumpNextRenderTargets)}}Yt.EndPerformanceCounter("Custom render targets",this.customRenderTargets.length>0),this._intermediateRendering=!1,this._renderId++}this._engine.currentRenderPassId=n?.renderPassId??Ze.RENDERPASS_MAIN,this.activeCamera=n,this._activeCamera&&this._activeCamera.cameraRigMode!==Ze.RIG_MODE_CUSTOM&&!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;e<this.activeCameras.length;e++)this._processSubCameras(this.activeCameras[e],e>0);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<this._toBeDisposed.length;e++){const t=this._toBeDisposed[e];t&&t.dispose()}this._toBeDisposed.length=0}this.dumpNextRenderTargets&&(this.dumpNextRenderTargets=!1),this._activeBones.addCount(0,!0),this._activeIndices.addCount(0,!0),this._activeParticles.addCount(0,!0),this._engine.restoreDefaultFramebuffer()}freezeMaterials(){for(let e=0;e<this.materials.length;e++)this.materials[e].freeze()}unfreezeMaterials(){for(let e=0;e<this.materials.length;e++)this.materials[e].unfreeze()}dispose(){if(this.isDisposed)return;this.beforeRender=null,this.afterRender=null,this.metadata=null,this.skeletons.length=0,this.morphTargetManagers.length=0,this._transientComponents.length=0,this._isReadyForMeshStage.clear(),this._beforeEvaluateActiveMeshStage.clear(),this._evaluateSubMeshStage.clear(),this._preActiveMeshStage.clear(),this._cameraDrawRenderTargetStage.clear(),this._beforeCameraDrawStage.clear(),this._beforeRenderTargetDrawStage.clear(),this._beforeRenderingGroupDrawStage.clear(),this._beforeRenderingMeshStage.clear(),this._afterRenderingMeshStage.clear(),this._afterRenderingGroupDrawStage.clear(),this._afterCameraDrawStage.clear(),this._afterRenderTargetDrawStage.clear(),this._afterRenderStage.clear(),this._beforeCameraUpdateStage.clear(),this._beforeClearStage.clear(),this._gatherRenderTargetsStage.clear(),this._gatherActiveCameraRenderTargetsStage.clear(),this._pointerMoveStage.clear(),this._pointerDownStage.clear(),this._pointerUpStage.clear(),this.importedMeshesFiles=[],this.stopAllAnimations&&(this._activeAnimatables.forEach((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){de.Error("An error occurred while calling onDisposeObservable!",e)}this.detachControl();if(this._engine.getInputElement())for(let e=0;e<this.cameras.length;e++)this.cameras[e].detachControl();this._disposeList(this.animationGroups),this._disposeList(this.lights),this._disposeList(this.meshes,(e=>e.dispose(!0))),this._disposeList(this.transformNodes,(e=>e.dispose(!0)));const t=this.cameras;this._disposeList(t),this._defaultMaterial&&this._defaultMaterial.dispose(),this._disposeList(this.multiMaterials),this._disposeList(this.materials),this._disposeList(this.particleSystems),this._disposeList(this.postProcesses),this._disposeList(this.textures),this._disposeList(this.morphTargetManagers),this._sceneUbo.dispose(),this._multiviewSceneUbo&&this._multiviewSceneUbo.dispose(),this.postProcessManager.dispose(),this._disposeList(this._components);let i=this._engine.scenes.indexOf(this);i>-1&&this._engine.scenes.splice(i,1),y._LastCreatedScene===this&&(this._engine.scenes.length>0?y._LastCreatedScene=this._engine.scenes[this._engine.scenes.length-1]:y._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._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<this.meshes.length;e++){const t=this.meshes[e].geometry;t&&t.clearCachedData()}}cleanCachedTextureBuffer(){for(const e of this.textures){e._buffer&&(e._buffer=null)}}getWorldExtends(e){const t=new B(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),i=new B(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);return e=e||(()=>!0),this.meshes.filter(e).forEach((e=>{if(e.computeWorldMatrix(!0),!e.subMeshes||0===e.subMeshes.length||e.infiniteDistance)return;const n=e.getBoundingInfo(),r=n.boundingBox.minimumWorld,s=n.boundingBox.maximumWorld;B.CheckExtends(r,t,i),B.CheckExtends(s,t,i)})),{min:t,max:i}}createPickingRay(e,t,i,n,r=!1){throw Y("Ray")}createPickingRayToRef(e,t,i,n,r,s=!1,a=!1){throw Y("Ray")}createPickingRayInCameraSpace(e,t,i){throw Y("Ray")}createPickingRayInCameraSpaceToRef(e,t,i,n){throw Y("Ray")}get _pickingAvailable(){return!1}pick(e,t,i,n,r,s){const a=Y("Ray",!0);return a&&de.Warn(a),new Ci}pickWithBoundingInfo(e,t,i,n,r){const s=Y("Ray",!0);return s&&de.Warn(s),new Ci}pickWithRay(e,t,i,n){throw Y("Ray")}multiPick(e,t,i,n,r){throw Y("Ray")}multiPickWithRay(e,t,i){throw Y("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(Ze.MATERIAL_TextureDirtyFlag)}_getByTags(e,t,i){if(void 0===t)return e;const n=[];for(const r in e){const s=e[r];q&&q.MatchesQuery(s,t)&&(!i||i(s))&&n.push(s)}return n}getMeshesByTags(e,t){return this._getByTags(this.meshes,e,t)}getCamerasByTags(e,t){return this._getByTags(this.cameras,e,t)}getLightsByTags(e,t){return this._getByTags(this.lights,e,t)}getMaterialByTags(e,t){return this._getByTags(this.materials,e,t).concat(this._getByTags(this.multiMaterials,e,t))}getTransformNodesByTags(e,t){return this._getByTags(this.transformNodes,e,t)}setRenderingOrder(e,t=null,i=null,n=null){this._renderingManager.setRenderingOrder(e,t,i,n)}setRenderingAutoClearDepthStencil(e,t,i=!0,n=!0){this._renderingManager.setRenderingAutoClearDepthStencil(e,t,i,n)}getAutoClearDepthStencilSetup(e){return this._renderingManager.getAutoClearDepthStencilSetup(e)}_forceBlockMaterialDirtyMechanism(e){this._blockMaterialDirtyMechanism=e}get blockMaterialDirtyMechanism(){return this._blockMaterialDirtyMechanism}set blockMaterialDirtyMechanism(e){this._blockMaterialDirtyMechanism!==e&&(this._blockMaterialDirtyMechanism=e,e||this.markAllMaterialsAsDirty(Ze.MATERIAL_AllDirtyFlag))}markAllMaterialsAsDirty(e,t){if(!this._blockMaterialDirtyMechanism)for(const i of this.materials)t&&!t(i)||i.markAsDirty(e)}_loadFile(e,t,i,n,r,s,a){const o=Ot(e,t,i,n?this.offlineProvider:void 0,r,s,a);return this._activeRequests.push(o),o.onCompleteObservable.add((e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)})),o}_loadFileAsync(e,t,i,n,r){return new Promise(((s,a)=>{this._loadFile(e,(e=>{s(e)}),t,i,n,((e,t)=>{a(t)}),r)}))}_requestFile(e,t,i,n,r,s,a){const o=Dt(e,t,i,n?this.offlineProvider:void 0,r,s,a);return this._activeRequests.push(o),o.onCompleteObservable.add((e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)})),o}_requestFileAsync(e,t,i,n,r){return new Promise(((s,a)=>{this._requestFile(e,(e=>{s(e)}),t,i,n,(e=>{a(e)}),r)}))}_readFile(e,t,i,n,r){const s=yt(e,t,i,n,r);return this._activeRequests.push(s),s.onCompleteObservable.add((e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)})),s}_readFileAsync(e,t,i){return new Promise(((n,r)=>{this._readFile(e,(e=>{n(e)}),t,i,(e=>{r(e)}))}))}getPerfCollector(){throw Y("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)}}Rr.FOGMODE_NONE=Ze.FOGMODE_NONE,Rr.FOGMODE_EXP=Ze.FOGMODE_EXP,Rr.FOGMODE_EXP2=Ze.FOGMODE_EXP2,Rr.FOGMODE_LINEAR=Ze.FOGMODE_LINEAR,Rr.MinDeltaTime=1,Rr.MaxDeltaTime=1e3,M("BABYLON.Scene",Rr),function(e){e[e.Clean=0]="Clean",e[e.Stop=1]="Stop",e[e.Sync=2]="Sync",e[e.NoSync=3]="NoSync"}(vr||(vr={}));const Sr=new g,Ir={};function Cr(){return Ir[".babylon"]}function Mr(e){const t=Ir[e];return t||(de.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"),Cr())}function xr(e,t,i,n,r,s,a,o,l){const c="data:"===(h=e.url).substr(0,5)?h.substr(5):null;var h;if(e.rawData&&!a)throw"When using ArrayBufferView to load data the file extension must be provided.";const d=a?Mr(a):c?function(e){for(const t in Ir){const i=Ir[t].plugin;if(i.canDirectLoad&&i.canDirectLoad(e))return Ir[t]}return Cr()}(e.url):function(e){const t=e.indexOf("?");-1!==t&&(e=e.substring(0,t));const i=e.lastIndexOf(".");return Mr(e.substring(i,e.length).toLowerCase())}(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.";const u=d.plugin.createPlugin?.(l??{})??d.plugin;if(!u)throw`The loader plugin corresponding to the '${a}' file type has not been found. If using es6, please import the plugin you wish to use before.`;if(Sr.notifyObservers(u),c&&(u.canDirectLoad&&u.canDirectLoad(e.url)||!Pt(e.url))){if(u.directLoad){const e=u.directLoad(t,c);e instanceof Promise?e.then((e=>{i(u,e)})).catch((e=>{r("Error in directLoad of _loadData: "+e,e)})):i(u,e)}else i(u,c);return u}const f=d.isBinary,_=(e,n)=>{t.isDisposed?r("Scene has been disposed"):i(u,e,n)};let m=null,p=!1;u.onDisposeObservable?.add((()=>{p=!0,m&&(m.abort(),m=null),s()}));const g=()=>{if(p)return;const i=(e,t)=>{r(e?.statusText,t)};if(!u.loadFile&&e.rawData)throw"Plugin does not support loading ArrayBufferView.";m=u.loadFile?u.loadFile(t,e.rawData||e.file||e.url,e.rootUrl,_,n,f,i,o):t._loadFile(e.file||e.url,_,n,!0,f,i)},E=t.getEngine();let T=E.enableOfflineSupport;if(T){let i=!1;for(const n of t.disableOfflineSupportExceptionRules)if(n.test(e.url)){i=!0;break}T=!i}return T&&vt.OfflineProviderFactory?t.offlineProvider=vt.OfflineProviderFactory(e.url,g,E.disableManifestCheck):g(),u}function br(e,t="",i=y.LastCreatedScene,n=null,r=null,s=null,a=null,o="",l={}){if(!i)return de.Error("No scene available to load asset container to"),null;const c=function(e,t){let i,n,r=null,s=null;if(t)if(t.name)i=`file:${t.name}`,n=t.name,r=t;else if(ArrayBuffer.isView(t))i="",n=Gt(),s=t;else if(t.startsWith("data:"))i=t,n="";else if(e){const r=t;if("/"===r.substr(0,1))return Yt.Error("Wrong sceneFilename parameter"),null;i=e+r,n=r}else i=t,n=Yt.GetFilename(t),e=Yt.GetFolderPath(t);else i=e,n=Yt.GetFilename(e),e=Yt.GetFolderPath(e);return{url:i,rootUrl:e,name:n,file:r,rawData:s}}(e,t);if(!c)return null;const h={};i.addPendingData(h);const d=()=>{i.removePendingData(h)},u=(e,t)=>{const n=function(e,t,i){let n="Unable to load from "+(e.rawData?"binary data":e.url);return t?n+=`: ${t}`:i&&(n+=`: ${i}`),n}(c,e,t);s?s(i,n,new Te(n,Ee.SceneLoaderError,t)):de.Error(n),d()},f=r?e=>{try{r(e)}catch(e){u("Error in onProgress callback",e)}}:void 0,_=e=>{if(n)try{n(e)}catch(e){u("Error in onSuccess callback",e)}i.removePendingData(h)};return xr(c,i,((e,t)=>{if(e.loadAssetContainer){const n=e.loadAssetContainer(i,t,c.rootUrl,u);if(!n)return;n.populateRootNodes(),i.loadingPluginName=e.name,_(n)}else if(e.loadAssetContainerAsync){e.loadAssetContainerAsync(i,t,c.rootUrl,f,c.name).then((t=>{t.populateRootNodes(),i.loadingPluginName=e.name,_(t)})).catch((e=>{u(e.message,e)}))}else u("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.")}),f,u,d,a,o,l)}function yr(e,t,i){const{rootUrl:n="",onProgress:r,pluginExtension:s,name:a,pluginOptions:o}=i??{};return function(e,t,i,n,r,s,a){return new Promise(((o,l)=>{br(e,t,i,(e=>{o(e)}),n,((e,t,i)=>{l(i||new Error(t))}),r,s,a)}))}(n,e,t,r,s,a,o)}class Or{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=Ze.TEXTURE_WRAP_ADDRESSMODE,this._wrapV=Ze.TEXTURE_WRAP_ADDRESSMODE,this.wrapR=Ze.TEXTURE_WRAP_ADDRESSMODE,this.anisotropicFilteringLevel=4,this.delayLoadState=Ze.DELAYLOADSTATE_NONE,this._texture=null,this._engine=null,this._cachedSize=gn.Zero(),this._cachedBaseSize=gn.Zero(),this._initialSamplingMode=Ze.TEXTURE_BILINEAR_SAMPLINGMODE,this._texture=Or._IsRenderTargetWrapper(e)?e.texture:e,this._texture&&(this._engine=this._texture.getEngine())}isReady(){return this.delayLoadState===Ze.DELAYLOADSTATE_NOTLOADED?(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)}}Ni.prototype._readTexturePixelsSync=function(e,t,i,n=-1,r=0,s=null,a=!0,o=!1,l=0,c=0){const h=this._gl;if(!h)throw new Error("Engine does not have gl rendering context.");if(!this._dummyFramebuffer){const e=h.createFramebuffer();if(!e)throw new Error("Unable to create dummy framebuffer");this._dummyFramebuffer=e}h.bindFramebuffer(h.FRAMEBUFFER,this._dummyFramebuffer),n>-1?h.framebufferTexture2D(h.FRAMEBUFFER,h.COLOR_ATTACHMENT0,h.TEXTURE_CUBE_MAP_POSITIVE_X+n,e._hardwareTexture?.underlyingResource,r):h.framebufferTexture2D(h.FRAMEBUFFER,h.COLOR_ATTACHMENT0,h.TEXTURE_2D,e._hardwareTexture?.underlyingResource,r);let d=void 0!==e.type?this._getWebGLTextureType(e.type):h.UNSIGNED_BYTE;if(o)s||(s=function(e,t,i=!1){switch(e){case Ze.TEXTURETYPE_BYTE:return ArrayBuffer,new Int8Array(t);case Ze.TEXTURETYPE_UNSIGNED_BYTE:return ArrayBuffer,new Uint8Array(t);case Ze.TEXTURETYPE_SHORT:return t instanceof ArrayBuffer?new Int16Array(t):new Int16Array(i?t/2:t);case Ze.TEXTURETYPE_UNSIGNED_SHORT:case Ze.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:case Ze.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:case Ze.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:case Ze.TEXTURETYPE_HALF_FLOAT:return t instanceof ArrayBuffer?new Uint16Array(t):new Uint16Array(i?t/2:t);case Ze.TEXTURETYPE_INT:return t instanceof ArrayBuffer?new Int32Array(t):new Int32Array(i?t/4:t);case Ze.TEXTURETYPE_UNSIGNED_INTEGER:case Ze.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:case Ze.TEXTURETYPE_UNSIGNED_INT_24_8:case Ze.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:case Ze.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:case Ze.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:return t instanceof ArrayBuffer?new Uint32Array(t):new Uint32Array(i?t/4:t);case Ze.TEXTURETYPE_FLOAT:return t instanceof ArrayBuffer?new Float32Array(t):new Float32Array(i?t/4:t)}return ArrayBuffer,new Uint8Array(t)}(e.type,4*t*i));else if(d===h.UNSIGNED_BYTE)s||(s=new Uint8Array(4*t*i)),d=h.UNSIGNED_BYTE;else s||(s=new Float32Array(4*t*i)),d=h.FLOAT;return a&&this.flushFramebuffer(),h.readPixels(l,c,t,i,h.RGBA,d,s),h.bindFramebuffer(h.FRAMEBUFFER,this._currentFramebuffer),s},Ni.prototype._readTexturePixels=function(e,t,i,n=-1,r=0,s=null,a=!0,o=!1,l=0,c=0){return Promise.resolve(this._readTexturePixelsSync(e,t,i,n,r,s,a,o,l,c))};class Dr extends Or{set hasAlpha(e){this._hasAlpha!==e&&(this._hasAlpha=e,this._scene&&this._scene.markAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag,(e=>e.hasTexture(this))))}get hasAlpha(){return this._hasAlpha}set getAlphaFromRGB(e){this._getAlphaFromRGB!==e&&(this._getAlphaFromRGB=e,this._scene&&this._scene.markAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag,(e=>e.hasTexture(this))))}get getAlphaFromRGB(){return this._getAlphaFromRGB}set coordinatesIndex(e){this._coordinatesIndex!==e&&(this._coordinatesIndex=e,this._scene&&this._scene.markAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag,(e=>e.hasTexture(this))))}get coordinatesIndex(){return this._coordinatesIndex}set coordinatesMode(e){this._coordinatesMode!==e&&(this._coordinatesMode=e,this._scene&&this._scene.markAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag,(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(Ze.MATERIAL_TextureDirtyFlag,(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(Ze.MATERIAL_TextureDirtyFlag,(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=Gt()),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=Ze.TEXTURE_EXPLICIT_MODE,this.wrapR=Ze.TEXTURE_WRAP_ADDRESSMODE,this.anisotropicFilteringLevel=Dr.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 g,this._onDisposeObserver=null,this._scene=null,this._uid=null,this._parentContainer=null,this._loadingError=!1,e?Dr._IsScene(e)?this._scene=e:this._engine=e:this._scene=y.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 k.IdentityReadOnly}getReflectionTextureMatrix(){return k.IdentityReadOnly}getRefractionTextureMatrix(){return this.getReflectionTextureMatrix()}isReadyOrNotBlocking(){return!this.isBlocking||this.isReady()||this.loadingError}scale(e){}get canRescale(){return!1}_getFromCache(e,t,i,n,r,s){const a=this._getEngine();if(!a)return null;const o=a._getUseSRGBBuffer(!!r,t),l=a.getLoadedTexturesCache();for(let a=0;a<l.length;a++){const c=l[a];if(!(void 0!==r&&o!==c._useSRGBBuffer||void 0!==n&&n!==c.invertY||c.url!==e||c.generateMipMaps!==!t||i&&i!==c.samplingMode||void 0!==s&&s!==c.isCube))return c.incrementReferences(),c}return null}_rebuild(e=!1){}clone(){return null}get textureType(){return this._texture&&void 0!==this._texture.type?this._texture.type:Ze.TEXTURETYPE_UNSIGNED_INT}get textureFormat(){return this._texture&&void 0!==this._texture.format?this._texture.format:Ze.TEXTUREFORMAT_RGBA}_markAllSubMeshesAsTexturesDirty(){const e=this.getScene();e&&e.markAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag)}readPixels(e=0,t=0,i=null,n=!0,r=!1,s=0,a=0,o=Number.MAX_VALUE,l=Number.MAX_VALUE){if(!this._texture)return null;const c=this._getEngine();if(!c)return null;const h=this.getSize();let d=h.width,u=h.height;0!==t&&(d/=Math.pow(2,t),u/=Math.pow(2,t),d=Math.round(d),u=Math.round(u)),o=Math.min(d,o),l=Math.min(u,l);try{return this._texture.isCube?c._readTexturePixels(this._texture,o,l,e,t,i,n,r,s,a):c._readTexturePixels(this._texture,o,l,-1,t,i,n,r,s,a)}catch(e){return null}}_readPixelsSync(e=0,t=0,i=null,n=!0,r=!1){if(!this._texture)return null;const s=this.getSize();let a=s.width,o=s.height;const l=this._getEngine();if(!l)return null;0!=t&&(a/=Math.pow(2,t),o/=Math.pow(2,t),a=Math.round(a),o=Math.round(o));try{return this._texture.isCube?l._readTexturePixelsSync(this._texture,a,o,e,t,i,n,r):l._readTexturePixelsSync(this._texture,a,o,-1,t,i,n,r)}catch(e){return null}}get _lodTextureHigh(){return this._texture?this._texture._lodTextureHigh:null}get _lodTextureMid(){return this._texture?this._texture._lodTextureMid:null}get _lodTextureLow(){return this._texture?this._texture._lodTextureLow:null}dispose(){if(this._scene){this._scene.stopAnimation&&this._scene.stopAnimation(this),this._scene.removePendingData(this);const e=this._scene.textures.indexOf(this);if(e>=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=re.Serialize(this);return re.AppendSerializedAnimations(this,t),t}static WhenAllReady(e,t){let i=e.length;if(0!==i)for(let n=0;n<e.length;n++){const r=e[n];if(r.isReady())0==--i&&t();else{const e=r.onLoadObservable;e?e.addOnce((()=>{0==--i&&t()})):0==--i&&t()}}else t()}static _IsScene(e){return"Scene"===e.getClassName()}}function Nr(e,t,i=!1){const n=t.width,r=t.height;if(e instanceof Float32Array){let t=e.byteLength/e.BYTES_PER_ELEMENT;const i=new Uint8Array(t);for(;--t>=0;){let n=e[t];n<0?n=0:n>1&&(n=1),i[t]=255*n}e=i}const s=document.createElement("canvas");s.width=n,s.height=r;const a=s.getContext("2d");if(!a)return null;const o=a.createImageData(n,r);if(o.data.set(e),a.putImageData(o,0,0),i){const e=document.createElement("canvas");e.width=n,e.height=r;const t=e.getContext("2d");return t?(t.translate(0,r),t.scale(1,-1),t.drawImage(s,0,0),e.toDataURL("image/png")):null}return s.toDataURL("image/png")}Dr.DEFAULT_ANISOTROPIC_FILTERING_LEVEL=4,e([a()],Dr.prototype,"uniqueId",void 0),e([a()],Dr.prototype,"name",void 0),e([a()],Dr.prototype,"metadata",void 0),e([a("hasAlpha")],Dr.prototype,"_hasAlpha",void 0),e([a("getAlphaFromRGB")],Dr.prototype,"_getAlphaFromRGB",void 0),e([a()],Dr.prototype,"level",void 0),e([a("coordinatesIndex")],Dr.prototype,"_coordinatesIndex",void 0),e([a()],Dr.prototype,"optimizeUVAllocation",void 0),e([a("coordinatesMode")],Dr.prototype,"_coordinatesMode",void 0),e([a()],Dr.prototype,"wrapU",null),e([a()],Dr.prototype,"wrapV",null),e([a()],Dr.prototype,"wrapR",void 0),e([a()],Dr.prototype,"anisotropicFilteringLevel",void 0),e([a()],Dr.prototype,"isCube",null),e([a()],Dr.prototype,"is3D",null),e([a()],Dr.prototype,"is2DArray",null),e([a()],Dr.prototype,"gammaSpace",null),e([a()],Dr.prototype,"invertZ",void 0),e([a()],Dr.prototype,"lodLevelInAlpha",void 0),e([a()],Dr.prototype,"lodGenerationOffset",null),e([a()],Dr.prototype,"lodGenerationScale",null),e([a()],Dr.prototype,"linearSpecularLOD",null),e([o()],Dr.prototype,"irradianceTexture",null),e([a()],Dr.prototype,"isRenderTarget",void 0);class Pr extends Dr{static _CreateVideoTexture(e,t,i,n=!1,r=!1,s=Pr.TRILINEAR_SAMPLINGMODE,a={},o,l=Ze.TEXTUREFORMAT_RGBA){throw Y("VideoTexture")}get noMipmap(){return this._noMipmap}get mimeType(){return this._mimeType}set isBlocking(e){this._isBlocking=e}get isBlocking(){return this._isBlocking}get invertY(){return this._invertY}constructor(e,t,i,n,r=Pr.TRILINEAR_SAMPLINGMODE,s=null,a=null,o=null,l=!1,c,h,d,u,f){let _;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 g,this._isBlocking=!0,this.name=e||"",this.url=e;let m=!1,p=null,E=!0;"object"==typeof i&&null!==i?(_=i.noMipmap??!1,n=i.invertY??!0,r=i.samplingMode??Pr.TRILINEAR_SAMPLINGMODE,s=i.onLoad??null,a=i.onError??null,o=i.buffer??null,l=i.deleteBuffer??!1,c=i.format,h=i.mimeType,d=i.loaderOptions,u=i.creationFlags,m=i.useSRGBBuffer??!1,p=i.internalTexture??null,E=i.gammaSpace??E):_=!!i,this._gammaSpace=E,this._noMipmap=_,this._invertY=void 0===n||n,this._initialSamplingMode=r,this._buffer=o,this._deleteBuffer=l,this._mimeType=h,this._loaderOptions=d,this._creationFlags=u,this._useSRGBBuffer=m,this._forcedExtension=f,c&&(this._format=c);const T=this.getScene(),A=this._getEngine();if(!A)return;A.onBeforeTextureInitObservable.notifyObservers(this);const v=()=>{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),s&&s(),!this.isBlocking&&T&&T.resetCachedMaterial()},R=(e,t)=>{this._loadingError=!0,this._errorObject={message:e,exception:t},a&&a(e,t),Pr.OnTextureLoadErrorObservable.notifyObservers(this)};if(!this.url&&!p)return this._delayedOnLoad=v,void(this._delayedOnError=R);if(this._texture=p??this._getFromCache(this.url,_,r,this._invertY,m,this.isCube),this._texture)if(this._texture.isReady)Qe.SetImmediate((()=>v()));else{const e=this._texture.onLoadedObservable.add(v);this._texture.onErrorObservable.add((t=>{R(t.message,t.exception),this._texture?.onLoadedObservable.remove(e)}))}else if(T&&T.useDelayedTextureLoading)this.delayLoadState=Ze.DELAYLOADSTATE_NOTLOADED,this._delayedOnLoad=v,this._delayedOnError=R;else{try{this._texture=A.createTexture(this.url,_,this._invertY,T,r,v,R,this._buffer,void 0,this._format,this._forcedExtension,h,d,u,m)}catch(e){throw R("error loading",e),e}l&&(this._buffer=null)}}updateURL(e,t=null,i,n){this.url&&(this.releaseInternalTexture(),this.getScene().markAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag,(e=>e.hasTexture(this)))),this.name&&!this.name.startsWith("data:")||(this.name=e),this.url=e,this._buffer=t,this._forcedExtension=n,this.delayLoadState=Ze.DELAYLOADSTATE_NOTLOADED,i&&(this._delayedOnLoad=i),this.delayLoad()}delayLoad(){if(this.delayLoadState!==Ze.DELAYLOADSTATE_NOTLOADED)return;const e=this.getScene();e&&(this.delayLoadState=Ze.DELAYLOADSTATE_LOADED,this._texture=this._getFromCache(this.url,this._noMipmap,this.samplingMode,this._invertY,this._useSRGBBuffer,this.isCube),this._texture?this._delayedOnLoad&&(this._texture.isReady?Qe.SetImmediate(this._delayedOnLoad):this._texture.onLoadedObservable.add(this._delayedOnLoad)):(this._texture=e.getEngine().createTexture(this.url,this._noMipmap,this._invertY,e,this.samplingMode,this._delayedOnLoad,this._delayedOnError,this._buffer,null,this._format,this._forcedExtension,this._mimeType,this._loaderOptions,this._creationFlags,this._useSRGBBuffer),this._deleteBuffer&&(this._buffer=null)),this._delayedOnLoad=null,this._delayedOnError=null)}_prepareRowForTextureGeneration(e,t,i,n){e*=this._cachedUScale,t*=this._cachedVScale,e-=this.uRotationCenter*this._cachedUScale,t-=this.vRotationCenter*this._cachedVScale,i-=this.wRotationCenter,B.TransformCoordinatesFromFloatsToRef(e,t,i,this._rowGenerationMatrix,n),n.x+=this.uRotationCenter*this._cachedUScale+this._cachedUOffset,n.y+=this.vRotationCenter*this._cachedVScale+this._cachedVOffset,n.z+=this.wRotationCenter}getTextureMatrix(e=1){if(this.uOffset===this._cachedUOffset&&this.vOffset===this._cachedVOffset&&this.uScale*e===this._cachedUScale&&this.vScale===this._cachedVScale&&this.uAng===this._cachedUAng&&this.vAng===this._cachedVAng&&this.wAng===this._cachedWAng&&this.uRotationCenter===this._cachedURotationCenter&&this.vRotationCenter===this._cachedVRotationCenter&&this.wRotationCenter===this._cachedWRotationCenter&&this.homogeneousRotationInUVTransform===this._cachedHomogeneousRotationInUVTransform)return this._cachedTextureMatrix;this._cachedUOffset=this.uOffset,this._cachedVOffset=this.vOffset,this._cachedUScale=this.uScale*e,this._cachedVScale=this.vScale,this._cachedUAng=this.uAng,this._cachedVAng=this.vAng,this._cachedWAng=this.wAng,this._cachedURotationCenter=this.uRotationCenter,this._cachedVRotationCenter=this.vRotationCenter,this._cachedWRotationCenter=this.wRotationCenter,this._cachedHomogeneousRotationInUVTransform=this.homogeneousRotationInUVTransform,this._cachedTextureMatrix&&this._rowGenerationMatrix||(this._cachedTextureMatrix=k.Zero(),this._rowGenerationMatrix=new k,this._t0=B.Zero(),this._t1=B.Zero(),this._t2=B.Zero()),k.RotationYawPitchRollToRef(this.vAng,this.uAng,this.wAng,this._rowGenerationMatrix),this.homogeneousRotationInUVTransform?(k.TranslationToRef(-this._cachedURotationCenter,-this._cachedVRotationCenter,-this._cachedWRotationCenter,H.Matrix[0]),k.TranslationToRef(this._cachedURotationCenter,this._cachedVRotationCenter,this._cachedWRotationCenter,H.Matrix[1]),k.ScalingToRef(this._cachedUScale,this._cachedVScale,0,H.Matrix[2]),k.TranslationToRef(this._cachedUOffset,this._cachedVOffset,0,H.Matrix[3]),H.Matrix[0].multiplyToRef(this._rowGenerationMatrix,this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(H.Matrix[1],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(H.Matrix[2],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(H.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),k.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(Ze.MATERIAL_TextureDirtyFlag,(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!==Pr.PROJECTION_MODE)return this._cachedReflectionTextureMatrix;if(this._cachedReflectionProjectionMatrixId===e.getProjectionMatrix().updateFlag)return this._cachedReflectionTextureMatrix}this._cachedReflectionTextureMatrix||(this._cachedReflectionTextureMatrix=k.Zero()),this._projectionModeMatrix||(this._projectionModeMatrix=k.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 Pr.PLANAR_MODE:k.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 Pr.PROJECTION_MODE:{k.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:k.IdentityToRef(this._cachedReflectionTextureMatrix)}return t&&e.markAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag,(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 re.Clone((()=>new Pr(this._texture?this._texture.url:null,this.getScene(),e)),this)}serialize(){const e=this.name;Pr.SerializeBuffers||this.name.startsWith("data:")&&(this.name=""),this.name.startsWith("data:")&&this.url===this.name&&(this.url="");const t=super.serialize(Pr._SerializeInternalTextureUniqueId);return t?((Pr.SerializeBuffers||Pr.ForceSerializeBuffers)&&("string"==typeof this._buffer&&"data:"===this._buffer.substr(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,"+Ae(this._buffer):(Pr.ForceSerializeBuffers||this.url&&this.url.startsWith("blob:")||this._forceSerialize)&&(t.base64String=!this._engine||this._engine._features.supportSyncTextureRead?function(e,t=0,i=0){const n=e.getInternalTexture();if(!n)return null;const r=e._readPixelsSync(t,i);return r?Nr(r,e.getSize(),n.invertY):null}(this):async function(e,t=0,i=0){const n=e.getInternalTexture();if(!n)return null;const r=await e.readPixels(t,i);return r?Nr(r,e.getSize(),n.invertY):null}(this))),t.invertY=this._invertY,t.samplingMode=this.samplingMode,t._creationFlags=this._creationFlags,t._useSRGBBuffer=this._useSRGBBuffer,Pr._SerializeInternalTextureUniqueId&&(t.internalTextureUniqueId=this._texture?.uniqueId??void 0),t.noMipmap=this._noMipmap,this.name=e,t):null}getClassName(){return"Texture"}dispose(){super.dispose(),this.onLoadObservable.clear(),this._delayedOnLoad=null,this._delayedOnError=null,this._buffer=null}static Parse(e,t,i){if(e.customType){const n=Bt.Instantiate(e.customType).Parse(e,t,i);return e.samplingMode&&n.updateSamplingMode&&n._samplingMode&&n._samplingMode!==e.samplingMode&&n.updateSamplingMode(e.samplingMode),n}if(e.isCube&&!e.isRenderTarget)return Pr._CubeTextureParser(e,t,i);const n=void 0!==e.internalTextureUniqueId;if(!e.name&&!e.isRenderTarget&&!n)return null;let r;if(n){const i=t.getEngine().getLoadedTexturesCache();for(const t of i)if(t.uniqueId===e.internalTextureUniqueId){r=t;break}}const s=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<e.animations.length;i++){const n=e.animations[i],r=x("BABYLON.Animation");r&&t.animations.push(r.Parse(n))}n&&!r&&t?._texture?._setUniqueId(e.internalTextureUniqueId)};return re.Parse((()=>{let n=!0;if(e.noMipmap&&(n=!1),e.mirrorPlane){const i=Pr._CreateMirror(e.name,e.renderTargetSize,t,n);return i._waitingRenderList=e.renderList,i.mirrorPlane=ei.FromArray(e.mirrorPlane),s(i),i}if(e.isRenderTarget){let i=null;if(e.isCube){if(t.reflectionProbes)for(let i=0;i<t.reflectionProbes.length;i++){const n=t.reflectionProbes[i];if(n.name===e.name)return n.cubeTexture}}else i=Pr._CreateRenderTargetTexture(e.name,e.renderTargetSize,t,n,e._creationFlags??0),i._waitingRenderList=e.renderList;return s(i),i}if(e.isVideo){const r=Pr._CreateVideoTexture(i+(e.url||e.name),i+(e.src||e.url),t,n,e.invertY,e.samplingMode,e.settings||{});return s(r),r}{let a;if(e.base64String&&!r)a=Pr.CreateFromBase64String(e.base64String,e.base64String,t,!n,e.invertY,e.samplingMode,(()=>{s(a)}),e._creationFlags??0,e._useSRGBBuffer??!1),a.name=e.name;else{let o;o=e.name&&(e.name.indexOf("://")>0||e.name.startsWith("data:"))?e.name:i+e.name,e.url&&(e.url.startsWith("data:")||Pr.UseSerializedUrlIfAny)&&(o=e.url);const l={noMipmap:!n,invertY:e.invertY,samplingMode:e.samplingMode,onLoad:()=>{s(a)},internalTexture:r};a=new Pr(o,t,l)}return a}}),e,t)}static CreateFromBase64String(e,t,i,n,r,s=Pr.TRILINEAR_SAMPLINGMODE,a=null,o=null,l=Ze.TEXTUREFORMAT_RGBA,c,h){return new Pr("data:"+t,i,n,r,s,a,o,e,!1,l,void 0,void 0,c,h)}static LoadFromDataString(e,t,i,n=!1,r,s=!0,a=Pr.TRILINEAR_SAMPLINGMODE,o=null,l=null,c=Ze.TEXTUREFORMAT_RGBA,h,d){return"data:"!==e.substr(0,5)&&(e="data:"+e),new Pr(e,i,r,s,a,o,l,t,n,c,void 0,void 0,h,d)}}Pr.SerializeBuffers=!0,Pr.ForceSerializeBuffers=!1,Pr.OnTextureLoadErrorObservable=new g,Pr._SerializeInternalTextureUniqueId=!1,Pr._CubeTextureParser=(e,t,i)=>{throw Y("CubeTexture")},Pr._CreateMirror=(e,t,i,n)=>{throw Y("MirrorTexture")},Pr._CreateRenderTargetTexture=(e,t,i,n,r)=>{throw Y("RenderTargetTexture")},Pr.NEAREST_SAMPLINGMODE=Ze.TEXTURE_NEAREST_SAMPLINGMODE,Pr.NEAREST_NEAREST_MIPLINEAR=Ze.TEXTURE_NEAREST_NEAREST_MIPLINEAR,Pr.BILINEAR_SAMPLINGMODE=Ze.TEXTURE_BILINEAR_SAMPLINGMODE,Pr.LINEAR_LINEAR_MIPNEAREST=Ze.TEXTURE_LINEAR_LINEAR_MIPNEAREST,Pr.TRILINEAR_SAMPLINGMODE=Ze.TEXTURE_TRILINEAR_SAMPLINGMODE,Pr.LINEAR_LINEAR_MIPLINEAR=Ze.TEXTURE_LINEAR_LINEAR_MIPLINEAR,Pr.NEAREST_NEAREST_MIPNEAREST=Ze.TEXTURE_NEAREST_NEAREST_MIPNEAREST,Pr.NEAREST_LINEAR_MIPNEAREST=Ze.TEXTURE_NEAREST_LINEAR_MIPNEAREST,Pr.NEAREST_LINEAR_MIPLINEAR=Ze.TEXTURE_NEAREST_LINEAR_MIPLINEAR,Pr.NEAREST_LINEAR=Ze.TEXTURE_NEAREST_LINEAR,Pr.NEAREST_NEAREST=Ze.TEXTURE_NEAREST_NEAREST,Pr.LINEAR_NEAREST_MIPNEAREST=Ze.TEXTURE_LINEAR_NEAREST_MIPNEAREST,Pr.LINEAR_NEAREST_MIPLINEAR=Ze.TEXTURE_LINEAR_NEAREST_MIPLINEAR,Pr.LINEAR_LINEAR=Ze.TEXTURE_LINEAR_LINEAR,Pr.LINEAR_NEAREST=Ze.TEXTURE_LINEAR_NEAREST,Pr.EXPLICIT_MODE=Ze.TEXTURE_EXPLICIT_MODE,Pr.SPHERICAL_MODE=Ze.TEXTURE_SPHERICAL_MODE,Pr.PLANAR_MODE=Ze.TEXTURE_PLANAR_MODE,Pr.CUBIC_MODE=Ze.TEXTURE_CUBIC_MODE,Pr.PROJECTION_MODE=Ze.TEXTURE_PROJECTION_MODE,Pr.SKYBOX_MODE=Ze.TEXTURE_SKYBOX_MODE,Pr.INVCUBIC_MODE=Ze.TEXTURE_INVCUBIC_MODE,Pr.EQUIRECTANGULAR_MODE=Ze.TEXTURE_EQUIRECTANGULAR_MODE,Pr.FIXED_EQUIRECTANGULAR_MODE=Ze.TEXTURE_FIXED_EQUIRECTANGULAR_MODE,Pr.FIXED_EQUIRECTANGULAR_MIRRORED_MODE=Ze.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE,Pr.CLAMP_ADDRESSMODE=Ze.TEXTURE_CLAMP_ADDRESSMODE,Pr.WRAP_ADDRESSMODE=Ze.TEXTURE_WRAP_ADDRESSMODE,Pr.MIRROR_ADDRESSMODE=Ze.TEXTURE_MIRROR_ADDRESSMODE,Pr.UseSerializedUrlIfAny=!1,e([a()],Pr.prototype,"url",void 0),e([a()],Pr.prototype,"uOffset",void 0),e([a()],Pr.prototype,"vOffset",void 0),e([a()],Pr.prototype,"uScale",void 0),e([a()],Pr.prototype,"vScale",void 0),e([a()],Pr.prototype,"uAng",void 0),e([a()],Pr.prototype,"vAng",void 0),e([a()],Pr.prototype,"wAng",void 0),e([a()],Pr.prototype,"uRotationCenter",void 0),e([a()],Pr.prototype,"vRotationCenter",void 0),e([a()],Pr.prototype,"wRotationCenter",void 0),e([a()],Pr.prototype,"homogeneousRotationInUVTransform",void 0),e([a()],Pr.prototype,"isBlocking",null),M("BABYLON.Texture",Pr),re._TextureParser=Pr.Parse;const Lr="postprocessVertexShader",Fr="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}";Je.ShadersStore[Lr]=Fr;const wr={name:Lr,shader:Fr};var Ur=Object.freeze({__proto__:null,postprocessVertexShader:wr});class Br{get depthStencilTexture(){return this._depthStencilTexture}get depthStencilTextureWithStencil(){return this._depthStencilTextureWithStencil}get isCube(){return this._isCube}get isMulti(){return this._isMulti}get is2DArray(){return this.layers>0}get is3D(){return this.depth>0}get size(){return this.width}get width(){return this._size.width||this._size}get height(){return this._size.height||this._size}get layers(){return this._size.layers||0}get depth(){return this._size.depth||0}get texture(){return this._textures?.[0]??null}get textures(){return this._textures}get faceIndices(){return this._faceIndices}get layerIndices(){return this._layerIndices}get samples(){return this._samples}setSamples(e,t=!0,i=!1){if(this.samples===e&&!i)return e;const n=this._isMulti?this._engine.updateMultipleRenderTargetTextureSampleCount(this,e,t):this._engine.updateRenderTargetTextureSampleCount(this,e);return this._samples=e,n}constructor(e,t,i,n,r){this._textures=null,this._faceIndices=null,this._layerIndices=null,this._samples=1,this._attachments=null,this._generateStencilBuffer=!1,this._generateDepthBuffer=!1,this._depthStencilTextureWithStencil=!1,this._isMulti=e,this._isCube=t,this._size=i,this._engine=n,this._depthStencilTexture=null,this.label=r}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,n=1,r=Ze.TEXTUREFORMAT_DEPTH32_FLOAT,s){return this._depthStencilTexture?.dispose(),this._depthStencilTextureWithStencil=i,this._depthStencilTextureLabel=s,this._depthStencilTexture=this._engine.createDepthStencilTexture(this._size,{bilinearFiltering:t,comparisonFunction:e,generateStencil:i,isCube:this._isCube,samples:n,depthTextureFormat:r,label:s},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,n=t.length,r=-1;const s=t[t.length-1]._source;14!==s&&12!==s||(i=!0,r=t[t.length-1].format,n--);const a=[],o=[],l=[],c=[],h=[],d=[],u=[],f={};for(let e=0;e<n;++e){const i=t[e];a.push(i.samplingMode),o.push(i.type),l.push(i.format);void 0!==f[i.uniqueId]?(c.push(-1),u.push(0)):(f[i.uniqueId]=e,i.is2DArray?(c.push(Ze.TEXTURE_2D_ARRAY),u.push(i.depth)):i.isCube?(c.push(Ze.TEXTURE_CUBE_MAP),u.push(0)):i.is3D?(c.push(Ze.TEXTURE_3D),u.push(i.depth)):(c.push(Ze.TEXTURE_2D),u.push(0))),this._faceIndices&&h.push(this._faceIndices[e]??0),this._layerIndices&&d.push(this._layerIndices[e]??0)}const _={samplingModes:a,generateMipMaps:t[0].generateMipMaps,generateDepthBuffer:this._generateDepthBuffer,generateStencilBuffer:this._generateStencilBuffer,generateDepthTexture:i,depthTextureFormat:r,types:o,formats:l,textureCount:n,targetTypes:c,faceIndex:h,layerIndex:d,layerCounts:u,label:this.label},m={width:this.width,height:this.height,depth:this.depth};e=this._engine.createMultipleRenderTarget(m,_);for(let i=0;i<n;++i){if(-1!==c[i])continue;const n=f[t[i].uniqueId];e.setTexture(e.textures[n],i)}}}else{const t={};if(t.generateDepthBuffer=this._generateDepthBuffer,t.generateMipMaps=this.texture?.generateMipMaps??!1,t.generateStencilBuffer=this._generateStencilBuffer,t.samplingMode=this.texture?.samplingMode,t.type=this.texture?.type,t.format=this.texture?.format,t.noColorAttachment=!this._textures,t.label=this.label,this.isCube)e=this._engine.createRenderTargetCubeTexture(this.width,t);else{const i={width:this.width,height:this.height,layers:this.is2DArray||this.is3D?this.texture?.depth:void 0};e=this._engine.createRenderTargetTexture(i,t)}e.texture&&(e.texture.isReady=!0)}return e}_swapRenderTargetWrapper(e){if(this._textures&&e._textures)for(let t=0;t<this._textures.length;++t)this._textures[t]._swapAndDie(e._textures[t],!1),e._textures[t].isReady=!0;this._depthStencilTexture&&e._depthStencilTexture&&(this._depthStencilTexture._swapAndDie(e._depthStencilTexture),e._depthStencilTexture.isReady=!0),this._textures=null,this._depthStencilTexture=null}_rebuild(){const e=this._cloneRenderTargetWrapper();if(e){if(this._depthStencilTexture){const t=this._depthStencilTexture.samplingMode,i=this._depthStencilTexture.format,n=t===Ze.TEXTURE_BILINEAR_SAMPLINGMODE||t===Ze.TEXTURE_TRILINEAR_SAMPLINGMODE||t===Ze.TEXTURE_LINEAR_LINEAR_MIPNEAREST;e.createDepthStencilTexture(this._depthStencilTexture._comparisonFunction,n,this._depthStencilTextureWithStencil,this._depthStencilTexture.samples,i,this._depthStencilTextureLabel)}this.samples>1&&e.setSamples(this.samples),e._swapRenderTargetWrapper(this),e.dispose()}}releaseTextures(){if(this._textures)for(let e=0;e<this._textures?.length;++e)this._textures[e].dispose();this._textures=null}dispose(e=!1){e||(this._depthStencilTexture?.dispose(),this._depthStencilTexture=null,this.releaseTextures()),this._engine._releaseRenderTargetWrapper(this)}}class Gr extends Br{constructor(e,t,i,n,r){super(e,t,i,n),this._framebuffer=null,this._depthStencilBuffer=null,this._MSAAFramebuffer=null,this._colorTextureArray=null,this._depthStencilTextureArray=null,this._disposeOnlyFramebuffers=!1,this._currentLOD=0,this._context=r}_cloneRenderTargetWrapper(){let e=null;return this._colorTextureArray&&this._depthStencilTextureArray?(e=this._engine.createMultiviewRenderTargetTexture(this.width,this.height),e.texture.isReady=!0):e=super._cloneRenderTargetWrapper(),e}_swapRenderTargetWrapper(e){super._swapRenderTargetWrapper(e),e._framebuffer=this._framebuffer,e._depthStencilBuffer=this._depthStencilBuffer,e._MSAAFramebuffer=this._MSAAFramebuffer,e._colorTextureArray=this._colorTextureArray,e._depthStencilTextureArray=this._depthStencilTextureArray,this._framebuffer=this._depthStencilBuffer=this._MSAAFramebuffer=this._colorTextureArray=this._depthStencilTextureArray=null}createDepthStencilTexture(e=0,t=!0,i=!1,n=1,r=Ze.TEXTUREFORMAT_DEPTH32_FLOAT,s){if(this._depthStencilBuffer){const e=this._engine,t=e._currentFramebuffer,i=this._context;e._bindUnboundFramebuffer(this._framebuffer),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,i.RENDERBUFFER,null),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.RENDERBUFFER,null),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.STENCIL_ATTACHMENT,i.RENDERBUFFER,null),e._bindUnboundFramebuffer(t),i.deleteRenderbuffer(this._depthStencilBuffer),this._depthStencilBuffer=null}return super.createDepthStencilTexture(e,t,i,n,r,s)}shareDepth(e){super.shareDepth(e);const t=this._context,i=this._depthStencilBuffer,n=e._MSAAFramebuffer||e._framebuffer,r=this._engine;e._depthStencilBuffer&&e._depthStencilBuffer!==i&&t.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=i;const s=e._generateStencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;r._bindUnboundFramebuffer(n),t.framebufferRenderbuffer(t.FRAMEBUFFER,s,t.RENDERBUFFER,i),r._bindUnboundFramebuffer(null)}_bindTextureRenderTarget(e,t=0,i,n=0){if(!e._hardwareTexture)return;const r=this._framebuffer,s=this._engine,a=s._currentFramebuffer;if(s._bindUnboundFramebuffer(r),s.webGLVersion>1){const r=this._context,s=r["COLOR_ATTACHMENT"+t];e.is2DArray||e.is3D?(i=i??this.layerIndices?.[t]??0,r.framebufferTextureLayer(r.FRAMEBUFFER,s,e._hardwareTexture.underlyingResource,n,i)):e.isCube?(i=i??this.faceIndices?.[t]??0,r.framebufferTexture2D(r.FRAMEBUFFER,s,r.TEXTURE_CUBE_MAP_POSITIVE_X+i,e._hardwareTexture.underlyingResource,n)):r.framebufferTexture2D(r.FRAMEBUFFER,s,r.TEXTURE_2D,e._hardwareTexture.underlyingResource,n)}else{const r=this._context,s=r["COLOR_ATTACHMENT"+t+"_WEBGL"],a=void 0!==i?r.TEXTURE_CUBE_MAP_POSITIVE_X+i:r.TEXTURE_2D;r.framebufferTexture2D(r.FRAMEBUFFER,s,a,e._hardwareTexture.underlyingResource,n)}s._bindUnboundFramebuffer(a)}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;e<i;e++){const t=this.textures[e];t&&(t.is2DArray||t.is3D?this._bindTextureRenderTarget(t,e,this.layerIndices[e]):t.isCube?this._bindTextureRenderTarget(t,e,this.faceIndices[e]):this._bindTextureRenderTarget(t,e))}}setLayerAndFaceIndex(e=0,t,i){if(super.setLayerAndFaceIndex(e,t,i),!this.textures||!this.layerIndices||!this.faceIndices)return;const n=this.textures[e];n.is2DArray||n.is3D?this._bindTextureRenderTarget(this.textures[e],e,this.layerIndices[e]):n.isCube&&this._bindTextureRenderTarget(this.textures[e],e,this.faceIndices[e])}dispose(e=this._disposeOnlyFramebuffers){const t=this._context;e||(this._colorTextureArray&&(this._context.deleteTexture(this._colorTextureArray),this._colorTextureArray=null),this._depthStencilTextureArray&&(this._context.deleteTexture(this._depthStencilTextureArray),this._depthStencilTextureArray=null)),this._framebuffer&&(t.deleteFramebuffer(this._framebuffer),this._framebuffer=null),this._depthStencilBuffer&&(t.deleteRenderbuffer(this._depthStencilBuffer),this._depthStencilBuffer=null),this._MSAAFramebuffer&&(t.deleteFramebuffer(this._MSAAFramebuffer),this._MSAAFramebuffer=null),super.dispose(e)}}vt.prototype.createDepthStencilTexture=function(e,t,i){if(t.isCube){const i=e.width||e;return this._createDepthStencilCubeTexture(i,t)}return this._createDepthStencilTexture(e,t,i)},Ni.prototype._createHardwareRenderTargetWrapper=function(e,t,i){const n=new Gr(e,t,i,this,this._gl);return this._renderTargetWrapperCache.push(n),n},Ni.prototype.createRenderTargetTexture=function(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!1,e);let n,r,s=!0,a=!1,o=!1,l=1;void 0!==t&&"object"==typeof t&&(s=t.generateDepthBuffer??!0,a=!!t.generateStencilBuffer,o=!!t.noColorAttachment,n=t.colorAttachment,l=t.samples??1,r=t.label);const c=n||(o?null:this._createInternalTexture(e,t,!0,5)),h=e.width||e,d=e.height||e,u=this._currentFramebuffer,f=this._gl,_=f.createFramebuffer();return this._bindUnboundFramebuffer(_),i._depthStencilBuffer=this._setupFramebufferDepthAttachments(a,s,h,d),!c||c.is2DArray||c.is3D||f.framebufferTexture2D(f.FRAMEBUFFER,f.COLOR_ATTACHMENT0,f.TEXTURE_2D,c._hardwareTexture.underlyingResource,0),this._bindUnboundFramebuffer(u),i.label=r??"RenderTargetWrapper",i._framebuffer=_,i._generateDepthBuffer=s,i._generateStencilBuffer=a,i.setTextures(c),this.updateRenderTargetTextureSampleCount(i,l),i},Ni.prototype._createDepthStencilTexture=function(e,t){const i=this._gl,n=e.layers||0,r=e.depth||0;let s=i.TEXTURE_2D;0!==n?s=i.TEXTURE_2D_ARRAY:0!==r&&(s=i.TEXTURE_3D);const a=new Et(this,12);if(a.label=t.label,!this._caps.depthTextureExtension)return de.Error("Depth texture is not supported by your browser or hardware."),a;const o={bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,...t};if(this._bindTextureDirectly(s,a,!0),this._setupDepthStencilTexture(a,e,o.generateStencil,0!==o.comparisonFunction&&o.bilinearFiltering,o.comparisonFunction,o.samples),void 0!==o.depthTextureFormat){if(o.depthTextureFormat!==Ze.TEXTUREFORMAT_DEPTH16&&o.depthTextureFormat!==Ze.TEXTUREFORMAT_DEPTH24&&o.depthTextureFormat!==Ze.TEXTUREFORMAT_DEPTH24UNORM_STENCIL8&&o.depthTextureFormat!==Ze.TEXTUREFORMAT_DEPTH24_STENCIL8&&o.depthTextureFormat!==Ze.TEXTUREFORMAT_DEPTH32_FLOAT&&o.depthTextureFormat!==Ze.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8)return de.Error("Depth texture format is not supported."),a;a.format=o.depthTextureFormat}else a.format=o.generateStencil?Ze.TEXTUREFORMAT_DEPTH24_STENCIL8:Ze.TEXTUREFORMAT_DEPTH24;const l=a.format===Ze.TEXTUREFORMAT_DEPTH24UNORM_STENCIL8||a.format===Ze.TEXTUREFORMAT_DEPTH24_STENCIL8||a.format===Ze.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8;let c=i.UNSIGNED_INT;a.format===Ze.TEXTUREFORMAT_DEPTH16?c=i.UNSIGNED_SHORT:a.format===Ze.TEXTUREFORMAT_DEPTH24UNORM_STENCIL8||a.format===Ze.TEXTUREFORMAT_DEPTH24_STENCIL8?c=i.UNSIGNED_INT_24_8:a.format===Ze.TEXTUREFORMAT_DEPTH32_FLOAT?c=i.FLOAT:a.format===Ze.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8&&(c=i.FLOAT_32_UNSIGNED_INT_24_8_REV);const h=l?i.DEPTH_STENCIL:i.DEPTH_COMPONENT;let d=h;return this.webGLVersion>1&&(a.format===Ze.TEXTUREFORMAT_DEPTH16?d=i.DEPTH_COMPONENT16:a.format===Ze.TEXTUREFORMAT_DEPTH24?d=i.DEPTH_COMPONENT24:a.format===Ze.TEXTUREFORMAT_DEPTH24UNORM_STENCIL8||a.format===Ze.TEXTUREFORMAT_DEPTH24_STENCIL8?d=i.DEPTH24_STENCIL8:a.format===Ze.TEXTUREFORMAT_DEPTH32_FLOAT?d=i.DEPTH_COMPONENT32F:a.format===Ze.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8&&(d=i.DEPTH32F_STENCIL8)),a.is2DArray?i.texImage3D(s,0,d,a.width,a.height,n,0,h,c,null):a.is3D?i.texImage3D(s,0,d,a.width,a.height,r,0,h,c,null):i.texImage2D(s,0,d,a.width,a.height,0,h,c,null),this._bindTextureDirectly(s,null),this._internalTexturesCache.push(a),a},Ni.prototype.updateRenderTargetTextureSampleCount=function(e,t){if(this.webGLVersion<2||!e||!e.texture)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 n=e.texture._hardwareTexture;if(n.releaseMSAARenderBuffers(),t>1&&"function"==typeof i.renderbufferStorageMultisample){const r=i.createFramebuffer();if(!r)throw new Error("Unable to create multi sampled framebuffer");e._MSAAFramebuffer=r,this._bindUnboundFramebuffer(e._MSAAFramebuffer);const s=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(!s)throw new Error("Unable to create multi sampled framebuffer");n.addMSAARenderBuffer(s)}else this._bindUnboundFramebuffer(e._framebuffer);return e.texture.samples=t,e._samples=t,e._depthStencilBuffer=this._setupFramebufferDepthAttachments(e._generateStencilBuffer,e._generateDepthBuffer,e.texture.width,e.texture.height,t),this._bindUnboundFramebuffer(null),t},Ni.prototype._setupDepthStencilTexture=function(e,t,i,n,r,s=1){const a=t.width||t,o=t.height||t,l=t.layers||0,c=t.depth||0;e.baseWidth=a,e.baseHeight=o,e.width=a,e.height=o,e.is2DArray=l>0,e.depth=l||c,e.isReady=!0,e.samples=s,e.generateMipMaps=!1,e.samplingMode=n?Ze.TEXTURE_BILINEAR_SAMPLINGMODE:Ze.TEXTURE_NEAREST_SAMPLINGMODE,e.type=Ze.TEXTURETYPE_UNSIGNED_INT,e._comparisonFunction=r;const h=this._gl,d=this._getTextureTarget(e),u=this._getSamplingParameters(e.samplingMode,!1);h.texParameteri(d,h.TEXTURE_MAG_FILTER,u.mag),h.texParameteri(d,h.TEXTURE_MIN_FILTER,u.min),h.texParameteri(d,h.TEXTURE_WRAP_S,h.CLAMP_TO_EDGE),h.texParameteri(d,h.TEXTURE_WRAP_T,h.CLAMP_TO_EDGE),this.webGLVersion>1&&(0===r?(h.texParameteri(d,h.TEXTURE_COMPARE_FUNC,Ze.LEQUAL),h.texParameteri(d,h.TEXTURE_COMPARE_MODE,h.NONE)):(h.texParameteri(d,h.TEXTURE_COMPARE_FUNC,r),h.texParameteri(d,h.TEXTURE_COMPARE_MODE,h.COMPARE_REF_TO_TEXTURE)))},vt.prototype.setTextureFromPostProcess=function(e,t,i){let n=null;t&&(t._forcedOutputTexture?n=t._forcedOutputTexture:t._textures.data[t._currentRenderTextureInd]&&(n=t._textures.data[t._currentRenderTextureInd])),this._bindTexture(e,n?.texture??null,i)},vt.prototype.setTextureFromPostProcessOutput=function(e,t,i){this._bindTexture(e,t?._outputTexture?.texture??null,i)},dt.prototype.setTextureFromPostProcess=function(e,t){this._engine.setTextureFromPostProcess(this._samplers[e],t,e)},dt.prototype.setTextureFromPostProcessOutput=function(e,t){this._engine.setTextureFromPostProcessOutput(this._samplers[e],t,e)};class Vr{static RegisterShaderCodeProcessing(e,t){t?Vr._CustomShaderCodeProcessing[e??""]=t:delete Vr._CustomShaderCodeProcessing[e??""]}static _GetShaderCodeProcessing(e){return Vr._CustomShaderCodeProcessing[e]??Vr._CustomShaderCodeProcessing[""]}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,n,r,s,a=Ze.TEXTURE_NEAREST_SAMPLINGMODE,o,l,c=null,h=Ze.TEXTURETYPE_UNSIGNED_INT,d="postprocess",u,f=!1,_=Ze.TEXTUREFORMAT_RGBA,m,p){this._parentContainer=null,this.width=-1,this.height=-1,this.nodeMaterialSource=null,this._outputTexture=null,this.autoClear=!0,this.forceAutoClearInAlphaMode=!1,this.alphaMode=Ze.ALPHA_DISABLE,this.animations=[],this.enablePixelPerfectMode=!1,this.forceFullscreenViewport=!0,this.scaleMode=Ze.SCALEMODE_FLOOR,this.alwaysForcePOT=!1,this._samples=1,this.adaptScaleToCurrentViewport=!1,this._shadersLoaded=!1,this._webGPUReady=!1,this._reusable=!1,this._renderId=0,this.externalTextureSamplerBinding=!1,this._textures=new Zt(2),this._textureCache=[],this._currentRenderTextureInd=0,this._scaleRatio=new U(1,1),this._texelSize=U.Zero(),this.onEffectCreatedObservable=new g(void 0,!0),this.onActivateObservable=new g,this.onSizeChangedObservable=new g,this.onApplyObservable=new g,this.onBeforeRenderObservable=new g,this.onAfterRenderObservable=new g,this._importPromises=[],this.name=e;let E=1,T=null;if(i&&!Array.isArray(i)){const e=i;i=e.uniforms??null,n=e.samplers??null,E=e.size??1,s=e.camera??null,a=e.samplingMode??Ze.TEXTURE_NEAREST_SAMPLINGMODE,o=e.engine,l=e.reusable,c=e.defines??null,h=e.textureType??Ze.TEXTURETYPE_UNSIGNED_INT,d=e.vertexUrl??"postprocess",u=e.indexParameters,f=e.blockCompilation??!1,_=e.textureFormat??Ze.TEXTUREFORMAT_RGBA,m=e.shaderLanguage??0,T=e.uniformBuffers??null}else r&&(E="number"==typeof r?r:{width:r.width,height:r.height});null!=s?(this._camera=s,this._scene=s.getScene(),s.attachPostProcess(this),this._engine=this._scene.getEngine(),this._scene.postProcesses.push(this),this.uniqueId=this._scene.getUniqueId()):o&&(this._engine=o,this._engine.postProcesses.push(this)),this._options=E,this.renderTargetSamplingMode=a||Ze.TEXTURE_NEAREST_SAMPLINGMODE,this._reusable=l||!1,this._textureType=h,this._textureFormat=_,this._shaderLanguage=m||0,this._samplers=n||[],this._samplers.push("textureSampler"),this._fragmentUrl=t,this._vertexUrl=d,this._parameters=i||[],this._parameters.push("scale"),this._uniformBuffers=T||[],this._indexParameters=u,this._drawWrapper=new pi(this._engine),this._webGPUReady=1===this._shaderLanguage,this._postConstructor(f,c,p)}_gatherImports(e=!1,t){e&&this._webGPUReady?t.push(Promise.all([Promise.resolve().then((function(){return hu}))])):t.push(Promise.all([Promise.resolve().then((function(){return Ur}))]))}_postConstructor(e,t=null,i){const n=this.getEngine().isWebGPU&&!Vr.ForceGLSL;this._gatherImports(n,this._importPromises),i&&i(n,this._importPromises),n&&this._webGPUReady&&(this._shaderLanguage=1),e||this.updateEffect(t)}getClassName(){return"PostProcess"}getEngine(){return this._engine}getEffect(){return this._drawWrapper.effect}shareOutputWith(e){return this._disposeTextures(),this._shareOutputWithPostProcess=e,this}useOwnOutput(){0==this._textures.length&&(this._textures=new Zt(2)),this._shareOutputWithPostProcess=null}updateEffect(e=null,t=null,i=null,n,r,s,a,o){const l=Vr._GetShaderCodeProcessing(this.name);if(l?.defineCustomBindings){const n=t?.slice()??[];n.push(...this._parameters);const r=i?.slice()??[];r.push(...this._samplers),e=l.defineCustomBindings(this.name,e,n,r),t=n,i=r}this._postProcessDefines=e,this._drawWrapper.effect=this._engine.createEffect({vertex:a??this._vertexUrl,fragment:o??this._fragmentUrl},{attributes:["position"],uniformsNames:t||this._parameters,uniformBuffersNames:this._uniformBuffers,samplers:i||this._samplers,defines:null!==e?e:"",fallbacks:null,onCompiled:r??null,onError:s??null,indexParameters:n||this._indexParameters,processCodeAfterIncludes:l?.processCodeAfterIncludes?(e,t)=>l.processCodeAfterIncludes(this.name,e,t):null,processFinalCode:l?.processFinalCode?(e,t)=>l.processFinalCode(this.name,e,t):null,shaderLanguage:this._shaderLanguage,extraInitializationsAsync:this._shadersLoaded?void 0:async()=>{await Promise.all(this._importPromises),this._shadersLoaded=!0}},this._engine),this.onEffectCreatedObservable.notifyObservers(this._drawWrapper.effect)}isReusable(){return this._reusable}markTextureDirty(){this.width=-1}_createRenderTargetTexture(e,t,i=0){for(let n=0;n<this._textureCache.length;n++)if(this._textureCache[n].texture.width===e.width&&this._textureCache[n].texture.height===e.height&&this._textureCache[n].postProcessChannel===i&&this._textureCache[n].texture._generateDepthBuffer===t.generateDepthBuffer&&this._textureCache[n].texture.samples===t.samples)return this._textureCache[n].texture;const n=this._engine.createRenderTargetTexture(e,t);return this._textureCache.push({texture:n,postProcessChannel:i,lastUsedRenderId:-1}),n}_flushTextureCache(){const e=this._renderId;for(let t=this._textureCache.length-1;t>=0;t--)if(e-this._textureCache[t].lastUsedRenderId>100){let e=!1;for(let i=0;i<this._textures.length;i++)if(this._textures.data[i]===this._textureCache[t].texture){e=!0;break}e||(this._textureCache[t].texture.dispose(),this._textureCache.splice(t,1))}}resize(e,t,i=null,n=!1,r=!1){this._textures.length>0&&this._textures.reset(),this.width=e,this.height=t;let s=null;if(i)for(let e=0;e<i._postProcesses.length;e++)if(null!==i._postProcesses[e]){s=i._postProcesses[e];break}const a={width:this.width,height:this.height},o={generateMipMaps:n,generateDepthBuffer:r||s===this,generateStencilBuffer:(r||s===this)&&this._engine.isStencilEnable,samplingMode:this.renderTargetSamplingMode,type:this._textureType,format:this._textureFormat,samples:this._samples,label:"PostProcessRTT-"+this.name};this._textures.push(this._createRenderTargetTexture(a,o,0)),this._reusable&&this._textures.push(this._createRenderTargetTexture(a,o,1)),this._texelSize.copyFromFloats(1/this.width,1/this.height),this.onSizeChangedObservable.notifyObservers(this)}_getTarget(){let e;if(this._shareOutputWithPostProcess)e=this._shareOutputWithPostProcess.inputTexture;else if(this._forcedOutputTexture)e=this._forcedOutputTexture,this.width=this._forcedOutputTexture.width,this.height=this._forcedOutputTexture.height;else{let t;e=this.inputTexture;for(let i=0;i<this._textureCache.length;i++)if(this._textureCache[i].texture===e){t=this._textureCache[i];break}t&&(t.lastUsedRenderId=this._renderId)}return e}activate(e,t=null,i){const n=(e=e||this._camera).getScene(),r=n.getEngine(),s=r.getCaps().maxTextureSize,a=(t?t.width:this._engine.getRenderWidth(!0))*this._options|0,o=(t?t.height:this._engine.getRenderHeight(!0))*this._options|0;let l=this._options.width||a,c=this._options.height||o;const h=this.renderTargetSamplingMode!==Ze.TEXTURE_NEAREST_LINEAR&&this.renderTargetSamplingMode!==Ze.TEXTURE_NEAREST_NEAREST&&this.renderTargetSamplingMode!==Ze.TEXTURE_LINEAR_LINEAR;let d=null;if(!this._shareOutputWithPostProcess&&!this._forcedOutputTexture){if(this.adaptScaleToCurrentViewport){const e=r.currentViewport;e&&(l*=e.width,c*=e.height)}(h||this.alwaysForcePOT)&&(this._options.width||(l=r.needPOTTextures?zt(l,s,this.scaleMode):l),this._options.height||(c=r.needPOTTextures?zt(c,s,this.scaleMode):c)),this.width===l&&this.height===c&&(d=this._getTarget())||this.resize(l,c,e,h,i),this._textures.forEach((e=>{e.samples!==this.samples&&this._engine.updateRenderTargetTextureSampleCount(e,this.samples)})),this._flushTextureCache(),this._renderId++}return d||(d=this._getTarget()),this.enablePixelPerfectMode?(this._scaleRatio.copyFromFloats(a/l,o/c),this._engine.bindFramebuffer(d,0,a,o,this.forceFullscreenViewport)):(this._scaleRatio.copyFromFloats(1,1),this._engine.bindFramebuffer(d,0,void 0,void 0,this.forceFullscreenViewport)),this._engine._debugInsertMarker?.(`post process ${this.name} input`),this.onActivateObservable.notifyObservers(e),this.autoClear&&(this.alphaMode===Ze.ALPHA_DISABLE||this.forceAutoClearInAlphaMode)&&this._engine.clear(this.clearColor?this.clearColor:n.clearColor,n._allowPostProcessClearColor,!0,!0),this._reusable&&(this._currentRenderTextureInd=(this._currentRenderTextureInd+1)%2),d}get isSupported(){return this._drawWrapper.effect.isSupported}get aspectRatio(){return this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.aspectRatio:this._forcedOutputTexture?this._forcedOutputTexture.width/this._forcedOutputTexture.height:this.width/this.height}isReady(){return this._drawWrapper.effect?.isReady()??!1}apply(){if(!this._drawWrapper.effect?.isReady())return null;let e;return this._engine.enableEffect(this._drawWrapper),this._engine.setState(!1),this._engine.setDepthBuffer(!1),this._engine.setDepthWrite(!1),this._engine.setAlphaMode(this.alphaMode),this.alphaConstants&&this.getEngine().setAlphaConstants(this.alphaConstants.r,this.alphaConstants.g,this.alphaConstants.b,this.alphaConstants.a),e=this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.inputTexture:this._forcedOutputTexture?this._forcedOutputTexture:this.inputTexture,this.externalTextureSamplerBinding||this._drawWrapper.effect._bindTexture("textureSampler",e?.texture),this._drawWrapper.effect.setVector2("scale",this._scaleRatio),this.onApplyObservable.notifyObservers(this._drawWrapper.effect),Vr._GetShaderCodeProcessing(this.name)?.bindCustomBindings?.(this.name,this._drawWrapper.effect),this._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=re.Serialize(this),t=this.getCamera()||this._scene&&this._scene.activeCamera;return e.customType="BABYLON."+this.getClassName(),e.cameraId=t?t.id:null,e.reusable=this._reusable,e.textureType=this._textureType,e.fragmentUrl=this._fragmentUrl,e.parameters=this._parameters,e.samplers=this._samplers,e.options=this._options,e.defines=this._postProcessDefines,e.textureFormat=this._textureFormat,e.vertexUrl=this._vertexUrl,e.indexParameters=this._indexParameters,e}clone(){const e=this.serialize();e._engine=this._engine,e.cameraId=null;const t=Vr.Parse(e,this._scene,"");return t?(t.onActivateObservable=this.onActivateObservable.clone(),t.onSizeChangedObservable=this.onSizeChangedObservable.clone(),t.onApplyObservable=this.onApplyObservable.clone(),t.onBeforeRenderObservable=this.onBeforeRenderObservable.clone(),t.onAfterRenderObservable=this.onAfterRenderObservable.clone(),t._prePassEffectConfiguration=this._prePassEffectConfiguration,t):null}static Parse(e,t,i){const n=x(e.customType);if(!n||!n._Parse)return null;const r=t?t.getCameraById(e.cameraId):null;return n._Parse(e,r,t,i)}static _Parse(e,t,i,n){return re.Parse((()=>new Vr(e.name,e.fragmentUrl,e.parameters,e.samplers,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable,e.defines,e.textureType,e.vertexUrl,e.indexParameters,!1,e.textureFormat)),e,i,n)}}Vr.ForceGLSL=!1,Vr._CustomShaderCodeProcessing={},e([a()],Vr.prototype,"uniqueId",void 0),e([a()],Vr.prototype,"name",void 0),e([a()],Vr.prototype,"width",void 0),e([a()],Vr.prototype,"height",void 0),e([a()],Vr.prototype,"renderTargetSamplingMode",void 0),e([u()],Vr.prototype,"clearColor",void 0),e([a()],Vr.prototype,"autoClear",void 0),e([a()],Vr.prototype,"forceAutoClearInAlphaMode",void 0),e([a()],Vr.prototype,"alphaMode",void 0),e([a()],Vr.prototype,"alphaConstants",void 0),e([a()],Vr.prototype,"enablePixelPerfectMode",void 0),e([a()],Vr.prototype,"forceFullscreenViewport",void 0),e([a()],Vr.prototype,"scaleMode",void 0),e([a()],Vr.prototype,"alwaysForcePOT",void 0),e([a("samples")],Vr.prototype,"_samples",void 0),e([a()],Vr.prototype,"adaptScaleToCurrentViewport",void 0),M("BABYLON.PostProcess",Vr),Ni.prototype.createRenderTargetCubeTexture=function(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!0,e),n={generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:Ze.TEXTURETYPE_UNSIGNED_INT,samplingMode:Ze.TEXTURE_TRILINEAR_SAMPLINGMODE,format:Ze.TEXTUREFORMAT_RGBA,...t};n.generateStencilBuffer=n.generateDepthBuffer&&n.generateStencilBuffer,(n.type!==Ze.TEXTURETYPE_FLOAT||this._caps.textureFloatLinearFiltering)&&(n.type!==Ze.TEXTURETYPE_HALF_FLOAT||this._caps.textureHalfFloatLinearFiltering)||(n.samplingMode=Ze.TEXTURE_NEAREST_SAMPLINGMODE);const r=this._gl,s=new Et(this,5);this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,s,!0);const a=this._getSamplingParameters(n.samplingMode,n.generateMipMaps);n.type!==Ze.TEXTURETYPE_FLOAT||this._caps.textureFloat||(n.type=Ze.TEXTURETYPE_UNSIGNED_INT,de.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type")),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MAG_FILTER,a.mag),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MIN_FILTER,a.min),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE);for(let t=0;t<6;t++)r.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,this._getRGBABufferInternalSizedFormat(n.type,n.format),e,e,0,this._getInternalFormat(n.format),this._getWebGLTextureType(n.type),null);const o=r.createFramebuffer();return this._bindUnboundFramebuffer(o),i._depthStencilBuffer=this._setupFramebufferDepthAttachments(n.generateStencilBuffer,n.generateDepthBuffer,e,e),n.generateMipMaps&&r.generateMipmap(r.TEXTURE_CUBE_MAP),this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,null),this._bindUnboundFramebuffer(null),i._framebuffer=o,i._generateDepthBuffer=n.generateDepthBuffer,i._generateStencilBuffer=n.generateStencilBuffer,s.width=e,s.height=e,s.isReady=!0,s.isCube=!0,s.samples=1,s.generateMipMaps=n.generateMipMaps,s.samplingMode=n.samplingMode,s.type=n.type,s.format=n.format,this._internalTexturesCache.push(s),i.setTextures(s),i},Ni.prototype.setDepthStencilTexture=function(e,t,i,n){void 0!==e&&(t&&(this._boundUniforms[e]=t),i&&i.depthStencilTexture?this._setTexture(e,i,!1,!0,n):this._setTexture(e,null,void 0,void 0,n))};const kr={positions:[1,1,-1,1,-1,-1,1,-1],indices:[0,1,2,0,2,3]};class Xr{constructor(e,t=kr){this._fullscreenViewport=new $t(0,0,1,1);const i=t.positions??kr.positions,n=t.indices??kr.indices;this.engine=e,this._vertexBuffers={[si.PositionKind]:new si(e,i,si.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(Ze.MATERIAL_TriangleFillMode,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[si.PositionKind];e&&(e.dispose(),delete this._vertexBuffers[si.PositionKind]),this._indexBuffer&&this.engine._releaseBuffer(this._indexBuffer),this._onContextRestoredObserver&&(this.engine.onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)}}class Hr{get effect(){return this._drawWrapper.effect}set effect(e){this._drawWrapper.effect=e}constructor(e){let t;this.onApplyObservable=new g;const i=e.uniformNames||[];e.vertexShader?t={fragmentSource:e.fragmentShader,vertexSource:e.vertexShader,spectorName:e.name||"effectWrapper"}:(i.push("scale"),t={fragmentSource:e.fragmentShader,vertex:"postprocess",spectorName:e.name||"effectWrapper"},this.onApplyObservable.add((()=>{this.effect.setFloat2("scale",1,1)})));const n=e.defines?e.defines.join("\n"):"";this._drawWrapper=new pi(e.engine),e.useShaderStore?(t.fragment=t.fragmentSource,t.vertex||(t.vertex=t.vertexSource),delete t.fragmentSource,delete t.vertexSource,this.effect=e.engine.createEffect(t,e.attributeNames||["position"],i,e.samplerNames,n,void 0,e.onCompiled,void 0,void 0,e.shaderLanguage)):(this.effect=new dt(t,e.attributeNames||["position"],i,e.samplerNames,e.engine,n,void 0,e.onCompiled,void 0,void 0,void 0,e.shaderLanguage),this._onContextRestoredObserver=e.engine.onContextRestoredObservable.add((()=>{this.effect._pipelineContext=null,this.effect._prepareEffect()})))}dispose(e=!1){this._onContextRestoredObserver&&(this.effect.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null),this.effect.dispose()}}const Wr="passPixelShader",zr="varying vec2 vUV;uniform sampler2D textureSampler;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{gl_FragColor=texture2D(textureSampler,vUV);}";Je.ShadersStore[Wr]=zr;const Yr={name:Wr,shader:zr};var Kr=Object.freeze({__proto__:null,passPixelShader:Yr});let qr;function jr(){if(!qr){let e,t=null;const i={preserveDrawingBuffer:!0,depth:!1,stencil:!1,alpha:!0,premultipliedAlpha:!1,antialias:!1,failIfMajorPerformanceCaveat:!1};try{e=new OffscreenCanvas(100,100),t=new Ni(e,!1,i)}catch(n){e=document.createElement("canvas"),t=new Ni(e,!1,i)}y.Instances.pop(),y.OnEnginesDisposedObservable.add((e=>{t&&e!==t&&!t.isDisposed&&0===y.Instances.length&&function(){qr&&(qr.wrapper.dispose(),qr.renderer.dispose(),qr.engine.dispose());qr=null}()})),t.getCaps().parallelShaderCompile=void 0;const n=new Xr(t),r=new Hr({engine:t,name:Yr.name,fragmentShader:Yr.shader,samplerNames:["textureSampler"]});qr={canvas:e,engine:t,renderer:n,wrapper:r}}return qr}async function Qr(e,t,i,n,r="image/png",s,a){const o=await i.readPixels(0,0,e,t);Jr(e,t,new Uint8Array(o.buffer),n,r,s,!0,void 0,a)}function Zr(e,t,i,n="image/png",r,s=!1,a=!1,o){return new Promise((l=>{Jr(e,t,i,(e=>l(e)),n,r,s,a,o)}))}function Jr(e,t,i,n,r="image/png",s,a=!1,o=!1,l){const c=jr();if(c.engine.setSize(e,t,!0),i instanceof Float32Array){const e=new Uint8Array(i.length);let t=i.length;for(;t--;){const n=i[t];e[t]=Math.round(255*j.Clamp(n))}i=e}const h=c.engine.createRawTexture(i,e,t,Ze.TEXTUREFORMAT_RGBA,!1,!a,Ze.TEXTURE_NEAREST_NEAREST);c.renderer.setViewport(),c.renderer.applyEffectWrapper(c.wrapper),c.wrapper.effect._bindTexture("textureSampler",h),c.renderer.draw(),o?Yt.ToBlob(c.canvas,(e=>{const t=new FileReader;t.onload=e=>{const t=e.target.result;n&&n(t)},t.readAsArrayBuffer(e)}),r,l):Yt.EncodeScreenshotCanvasData(c.canvas,n,r,s,l),h.dispose()}Yt.DumpData=Jr,Yt.DumpDataAsync=Zr,Yt.DumpFramebuffer=Qr,dt.prototype.setDepthStencilTexture=function(e,t){this._engine.setDepthStencilTexture(this._samplers[e],this._uniforms[e],t,e)};class $r extends Pr{get renderList(){return this._renderList}set renderList(e){this._unObserveRenderList&&(this._unObserveRenderList(),this._unObserveRenderList=null),e&&(this._unObserveRenderList=I(e,this._renderListHasChanged)),this._renderList=e}get postProcesses(){return this._postProcesses}get _prePassEnabled(){return!!this._prePassRenderTarget&&this._prePassRenderTarget.enabled}set onAfterUnbind(e){this._onAfterUnbindObserver&&this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver),this._onAfterUnbindObserver=this.onAfterUnbindObservable.add(e)}set onBeforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)}set onAfterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)}set onClear(e){this._onClearObserver&&this.onClearObservable.remove(this._onClearObserver),this._onClearObserver=this.onClearObservable.add(e)}get renderPassIds(){return this._renderPassIds}get currentRefreshId(){return this._currentRefreshId}setMaterialForRendering(e,t){let i;i=Array.isArray(e)?e:[e];for(let e=0;e<i.length;++e)for(let n=0;n<this._renderPassIds.length;++n)i[e].setMaterialForRenderPass(this._renderPassIds[n],void 0!==t?Array.isArray(t)?t[n]:t:void 0)}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(Ze.MATERIAL_TextureDirtyFlag)}get boundingBoxSize(){return this._boundingBoxSize}get depthStencilTexture(){return this._renderTarget?._depthStencilTexture??null}constructor(e,t,i,n=!1,r=!0,s=Ze.TEXTURETYPE_UNSIGNED_INT,a=!1,o=Pr.TRILINEAR_SAMPLINGMODE,l=!0,c=!1,h=!1,d=Ze.TEXTUREFORMAT_RGBA,u=!1,f,_,m=!1,p=!1){let E,T=!0;if("object"==typeof n){const e=n;n=!!e.generateMipMaps,r=e.doNotChangeAspectRatio??!0,s=e.type??Ze.TEXTURETYPE_UNSIGNED_BYTE,a=!!e.isCube,o=e.samplingMode??Pr.TRILINEAR_SAMPLINGMODE,l=e.generateDepthBuffer??!0,c=!!e.generateStencilBuffer,h=!!e.isMulti,d=e.format??Ze.TEXTUREFORMAT_RGBA,u=!!e.delayAllocation,f=e.samples,_=e.creationFlags,m=!!e.noColorAttachment,p=!!e.useSRGBBuffer,E=e.colorAttachment,T=e.gammaSpace??T}if(super(null,i,!n,void 0,o,void 0,void 0,void 0,void 0,d),this._unObserveRenderList=null,this._renderListHasChanged=(e,t)=>{const i=this._renderList?this._renderList.length:0;(0===t&&i>0||0===i)&&this.getScene()?.meshes.forEach((e=>{e._markSubMeshesAsLightDirty()}))},this.renderParticles=!0,this.renderSprites=!1,this.forceLayerMaskCheck=!1,this.ignoreCameraViewport=!1,this.onBeforeBindObservable=new g,this.onAfterUnbindObservable=new g,this.onBeforeRenderObservable=new g,this.onAfterRenderObservable=new g,this.onClearObservable=new g,this.onResizeObservable=new g,this._cleared=!1,this.skipInitialClear=!1,this._currentRefreshId=-1,this._refreshRate=1,this._samples=1,this._canRescale=!0,this._renderTarget=null,this.boundingBoxPosition=B.Zero(),!(i=this.getScene()))return;const A=this.getScene().getEngine();this._gammaSpace=T,this._coordinatesMode=Pr.PROJECTION_MODE,this.renderList=[],this.name=e,this.isRenderTarget=!0,this._initialSizeParameter=t,this._renderPassIds=[],this._isCubeData=a,this._processSizeParameter(t),this.renderPassId=this._renderPassIds[0],this._resizeObserver=A.onResizeObservable.add((()=>{})),this._generateMipMaps=!!n,this._doNotChangeAspectRatio=r,this._renderingManager=new $n(i),this._renderingManager._useSceneAutoClearSetup=!0,h||(this._renderTargetOptions={generateMipMaps:n,type:s,format:this._format??void 0,samplingMode:this.samplingMode,generateDepthBuffer:l,generateStencilBuffer:c,samples:f,creationFlags:_,noColorAttachment:m,useSRGBBuffer:p,colorAttachment:E,label:this.name},this.samplingMode===Pr.NEAREST_SAMPLINGMODE&&(this.wrapU=Pr.CLAMP_ADDRESSMODE,this.wrapV=Pr.CLAMP_ADDRESSMODE),u||(a?(this._renderTarget=i.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions),this.coordinatesMode=Pr.INVCUBIC_MODE,this._textureMatrix=k.Identity()):this._renderTarget=i.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions),this._texture=this._renderTarget.texture,void 0!==f&&(this.samples=f)))}createDepthStencilTexture(e=0,t=!0,i=!1,n=1,r=Ze.TEXTUREFORMAT_DEPTH32_FLOAT,s){this._renderTarget?.createDepthStencilTexture(e,t,i,n,r,s)}_releaseRenderPassId(){if(this._scene){const e=this._scene.getEngine();for(let t=0;t<this._renderPassIds.length;++t)e.releaseRenderPassId(this._renderPassIds[t])}this._renderPassIds=[]}_createRenderPassId(){this._releaseRenderPassId();const e=this._scene.getEngine(),t=this._isCubeData?6:this.getRenderLayers()||1;for(let i=0;i<t;++i)this._renderPassIds[i]=e.createRenderPassId(`RenderTargetTexture - ${this.name}#${i}`)}_processSizeParameter(e,t=!0){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;t&&this._createRenderPassId()}get samples(){return this._renderTarget?.samples??this._samples}set samples(e){this._renderTarget&&(this._samples=this._renderTarget.setSamples(e))}resetRefreshCounter(){this._currentRefreshId=-1}get refreshRate(){return this._refreshRate}set refreshRate(e){this._refreshRate=e,this.resetRefreshCounter()}addPostProcess(e){if(!this._postProcessManager){const e=this.getScene();if(!e)return;this._postProcessManager=new Qn(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))}_shouldRender(){return-1===this._currentRefreshId||this.refreshRate===this._currentRefreshId?(this._currentRefreshId=1,!0):(this._currentRefreshId++,!1)}getRenderSize(){return this.getRenderWidth()}getRenderWidth(){return this._size.width?this._size.width:this._size}getRenderHeight(){return this._size.width?this._size.height:this._size}getRenderLayers(){const e=this._size.layers;if(e)return e;const t=this._size.depth;return t||0}disableRescaling(){this._canRescale=!1}get canRescale(){return this._canRescale}scale(e){const t=Math.max(1,this.getRenderSize()*e);this.resize(t)}getReflectionTextureMatrix(){return this.isCube?this._textureMatrix:super.getReflectionTextureMatrix()}resize(e){const t=this.isCube;this._renderTarget?.dispose(),this._renderTarget=null;const i=this.getScene();i&&(this._processSizeParameter(e,!1),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(){return this._render(!1,!1,!0)}_render(e=!1,t=!1,i=!1){const n=this.getScene();if(!n)return i;const r=n.getEngine();if(void 0!==this.useCameraPostProcesses&&(e=this.useCameraPostProcesses),this._waitingRenderList){if(!this.renderListPredicate){this.renderList=[];for(let e=0;e<this._waitingRenderList.length;e++){const t=this._waitingRenderList[e],i=n.getMeshById(t);i&&this.renderList.push(i)}}this._waitingRenderList=void 0}if(this.renderListPredicate){this.renderList?this.renderList.length=0:this.renderList=[];const e=this.getScene();if(!e)return i;const t=e.meshes;for(let e=0;e<t.length;e++){const i=t[e];this.renderListPredicate(i)&&this.renderList.push(i)}}const s=r.currentRenderPassId;this.onBeforeBindObservable.notifyObservers(this);const a=this.activeCamera??n.activeCamera,o=n.activeCamera;a&&(a!==n.activeCamera&&(n.setTransformMatrix(a.getViewMatrix(),a.getProjectionMatrix(!0)),n.activeCamera=a),r.setViewport(a.rigParent?a.rigParent.viewport:a.viewport,this.getRenderWidth(),this.getRenderHeight())),this._defaultRenderListPrepared=!1;let l=i;if(i){n.getViewMatrix()||n.updateTransformMatrix();const e=this.is2DArray||this.is3D?this.getRenderLayers():this.isCube?6:1;for(let t=0;t<e&&l;t++){let e=null;const s=this.renderList?this.renderList:n.getActiveMeshes().data,a=this.renderList?this.renderList.length:n.getActiveMeshes().length;r.currentRenderPassId=this._renderPassIds[t],this.onBeforeRenderObservable.notifyObservers(t),this.getCustomRenderList&&(e=this.getCustomRenderList(t,s,a)),e||(e=s),this._doNotChangeAspectRatio||n.updateTransformMatrix(!0);for(let t=0;t<e.length&&l;++t){const n=e[t];if(n.isEnabled()&&!n.isBlocked&&n.isVisible&&n.subMeshes)if(this.customIsReadyFunction){if(!this.customIsReadyFunction(n,this.refreshRate,i)){l=!1;continue}}else if(!n.isReady(!0)){l=!1;continue}}this.onAfterRenderObservable.notifyObservers(t),(this.is2DArray||this.is3D||this.isCube)&&(n.incrementRenderId(),n.resetCachedMaterial())}}else if(!this.is2DArray&&!this.is3D||this.isMulti)if(this.isCube&&!this.isMulti)for(let i=0;i<6;i++)this._renderToTarget(i,e,t,void 0,a),n.incrementRenderId(),n.resetCachedMaterial();else this._renderToTarget(0,e,t,void 0,a);else for(let i=0;i<this.getRenderLayers();i++)this._renderToTarget(0,e,t,i,a),n.incrementRenderId(),n.resetCachedMaterial();return this.onAfterUnbindObservable.notifyObservers(this),r.currentRenderPassId=s,o&&(n.activeCamera=o,this.activeCamera&&this.activeCamera!==n.activeCamera&&n.setTransformMatrix(n.activeCamera.getViewMatrix(),n.activeCamera.getProjectionMatrix(!0)),r.setViewport(n.activeCamera.viewport)),n.resetCachedMaterial(),l}_bestReflectionRenderTargetDimension(e,t){const i=e*t,n=Xt(i+16384/(128+i));return Math.min(Wt(e),n)}_prepareRenderingManager(e,t,i,n){const r=this.getScene();if(!r)return;this._renderingManager.reset();const s=r.getRenderId();for(let a=0;a<t;a++){const t=e[a];if(t&&!t.isBlocked){if(this.customIsReadyFunction){if(!this.customIsReadyFunction(t,this.refreshRate,!1)){this.resetRefreshCounter();continue}}else if(!t.isReady(0===this.refreshRate)){this.resetRefreshCounter();continue}if(!t._internalAbstractMeshDataInfo._currentLODIsUpToDate&&r.activeCamera&&(t._internalAbstractMeshDataInfo._currentLOD=r.customLODSelector?r.customLODSelector(t,this.activeCamera||r.activeCamera):t.getLOD(this.activeCamera||r.activeCamera),t._internalAbstractMeshDataInfo._currentLODIsUpToDate=!0),!t._internalAbstractMeshDataInfo._currentLOD)continue;let e,a=t._internalAbstractMeshDataInfo._currentLOD;if(a._preActivateForIntermediateRendering(s),e=!(!n||!i)&&!(t.layerMask&i.layerMask),t.isEnabled()&&t.isVisible&&t.subMeshes&&!e){if(a!==t&&a._activate(s,!0),t._activate(s,!0)&&t.subMeshes.length){t.isAnInstance?t._internalAbstractMeshDataInfo._actAsRegularMesh&&(a=t):a._internalAbstractMeshDataInfo._onlyForInstancesIntermediate=!1,a._internalAbstractMeshDataInfo._isActiveIntermediate=!0;for(let e=0;e<a.subMeshes.length;e++){const t=a.subMeshes[e];this._renderingManager.dispatch(t,a)}}t._postActivate()}}}for(let e=0;e<r.particleSystems.length;e++){const t=r.particleSystems[e],i=t.emitter;t.isStarted()&&i&&(!i.position||i.isEnabled())&&this._renderingManager.dispatchParticles(t)}}_bindFrameBuffer(e=0,t=0){const i=this.getScene();if(!i)return;const n=i.getEngine();this._renderTarget&&n.bindFramebuffer(this._renderTarget,this.isCube?e:void 0,void 0,void 0,this.ignoreCameraViewport,0,t)}_unbindFrameBuffer(e,t){this._renderTarget&&e.unBindFramebuffer(this._renderTarget,this.isCube,(()=>{this.onAfterRenderObservable.notifyObservers(t)}))}_prepareFrame(e,t,i,n){this._postProcessManager?this._prePassEnabled||this._postProcessManager._prepareFrame(this._texture,this._postProcesses):n&&e.postProcessManager._prepareFrame(this._texture)||this._bindFrameBuffer(t,i)}_renderToTarget(e,t,i,n=0,r=null){const s=this.getScene();if(!s)return;const a=s.getEngine();a._debugPushGroup?.(`render to face #${e} layer #${n}`,1),this._prepareFrame(s,e,n,t),this.is2DArray||this.is3D?(a.currentRenderPassId=this._renderPassIds[n],this.onBeforeRenderObservable.notifyObservers(n)):(a.currentRenderPassId=this._renderPassIds[e],this.onBeforeRenderObservable.notifyObservers(e));if(a.snapshotRendering&&a.snapshotRenderingMode===Ze.SNAPSHOTRENDERING_FAST)this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(a):this.skipInitialClear||a.clear(this.clearColor||s.clearColor,!0,!0,!0);else{let o=null;const l=this.renderList?this.renderList:s.getActiveMeshes().data,c=this.renderList?this.renderList.length:s.getActiveMeshes().length;this.getCustomRenderList&&(o=this.getCustomRenderList(this.is2DArray||this.is3D?n:e,l,c)),o?this._prepareRenderingManager(o,o.length,r,this.forceLayerMaskCheck):(this._defaultRenderListPrepared||(this._prepareRenderingManager(l,c,r,!this.renderList||this.forceLayerMaskCheck),this._defaultRenderListPrepared=!0),o=l);for(const t of s._beforeRenderTargetClearStage)t.action(this,e,n);this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(a):this.skipInitialClear||a.clear(this.clearColor||s.clearColor,!0,!0,!0),this._doNotChangeAspectRatio||s.updateTransformMatrix(!0);for(const t of s._beforeRenderTargetDrawStage)t.action(this,e,n);this._renderingManager.render(this.customRenderFunction,o,this.renderParticles,this.renderSprites);for(const t of s._afterRenderTargetDrawStage)t.action(this,e,n);const h=this._texture?.generateMipMaps??!1;this._texture&&(this._texture.generateMipMaps=!1),this._postProcessManager?this._postProcessManager._finalizeFrame(!1,this._renderTarget??void 0,e,this._postProcesses,this.ignoreCameraViewport):t&&s.postProcessManager._finalizeFrame(!1,this._renderTarget??void 0,e);for(const t of s._afterRenderTargetPostProcessStage)t.action(this,e,n);this._texture&&(this._texture.generateMipMaps=h),this._doNotChangeAspectRatio||s.updateTransformMatrix(!0),i&&Qr(this.getRenderWidth(),this.getRenderHeight(),a)}this._unbindFrameBuffer(a,e),this._texture&&this.isCube&&5===e&&a.generateMipMapsForCubemap(this._texture,!0),a._debugPopGroup?.(1)}setRenderingOrder(e,t=null,i=null,n=null){this._renderingManager.setRenderingOrder(e,t,i,n)}setRenderingAutoClearDepthStencil(e,t){this._renderingManager.setRenderingAutoClearDepthStencil(e,t),this._renderingManager._useSceneAutoClearSetup=!1}clone(){const e=this.getSize(),t=new $r(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<this.renderList.length;t++)e.renderList.push(this.renderList[t].id);return e}disposeFramebufferObjects(){this._renderTarget?.dispose(!0)}releaseInternalTexture(){this._renderTarget?.releaseTextures(),this._texture=null}dispose(){this.onResizeObservable.clear(),this.onClearObservable.clear(),this.onAfterRenderObservable.clear(),this.onAfterUnbindObservable.clear(),this.onBeforeBindObservable.clear(),this.onBeforeRenderObservable.clear(),this._postProcessManager&&(this._postProcessManager.dispose(),this._postProcessManager=null),this._prePassRenderTarget&&this._prePassRenderTarget.dispose(),this._releaseRenderPassId(),this.clearPostProcesses(!0),this._resizeObserver&&(this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver),this._resizeObserver=null),this.renderList=null;const e=this.getScene();if(!e)return;let t=e.customRenderTargets.indexOf(this);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.refreshRate===$r.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=$r.REFRESHRATE_RENDER_ONCE),this._postProcessManager&&this._postProcessManager._rebuild()}freeRenderingGroups(){this._renderingManager&&this._renderingManager.freeRenderingGroups()}getViewCount(){return 1}}$r.REFRESHRATE_RENDER_ONCE=0,$r.REFRESHRATE_RENDER_ONEVERYFRAME=1,$r.REFRESHRATE_RENDER_ONEVERYTWOFRAMES=2,Pr._CreateRenderTargetTexture=(e,t,i,n,r)=>new $r(e,t,i,n);class es extends Vr{getClassName(){return"PassPostProcess"}constructor(e,t,i=null,n,r,s,a=Ze.TEXTURETYPE_UNSIGNED_INT,o=!1){super(e,"pass",null,null,t,i,n,r,s,void 0,a,void 0,null,o)}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.all([Promise.resolve().then((function(){return _u}))]))):t.push(Promise.all([Promise.resolve().then((function(){return Kr}))])),super._gatherImports(e,t)}static _Parse(e,t,i,n){return re.Parse((()=>new es(e.name,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable)),e,i,n)}}M("BABYLON.PassPostProcess",es),vt._RescalePostProcessFactory=e=>new es("rescale",1,null,Ze.TEXTURE_BILINEAR_SAMPLINGMODE,e,!1,Ze.TEXTURETYPE_UNSIGNED_INT);Je.ShadersStore.lodPixelShader="#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 bool gamma;void main(void)\n{gl_FragColor=textureLod(textureSampler,vUV,lod);if (!gamma) {gl_FragColor.rgb=pow(gl_FragColor.rgb,vec3(GammaEncodePowerApprox));}}\n";let ts,is;function ns(e){ts||(ts=new Float32Array(1),is=new Int32Array(ts.buffer)),ts[0]=e;const t=is[0];let i=t>>16&32768,n=t>>12&2047;const r=t>>23&255;return r<103?i:r>142?(i|=31744,i|=(255==r?0:1)&&8388607&t,i):r<113?(n|=2048,i|=(n>>114-r)+(n>>113-r&1),i):(i|=r-112<<10|n>>1,i+=1&n,i)}function rs(e){const t=(32768&e)>>15,i=(31744&e)>>10,n=1023&e;return 0===i?(t?-1:1)*Math.pow(2,-14)*(n/Math.pow(2,10)):31==i?n?NaN:1/0*(t?-1:1):(t?-1:1)*Math.pow(2,i-15)*(1+n/Math.pow(2,10))}Je.ShadersStore.lodCubePixelShader="precision highp float;const float GammaEncodePowerApprox=1.0/2.2;varying vec2 vUV;uniform samplerCube textureSampler;uniform float lod;uniform bool gamma;void main(void)\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) {gl_FragColor.rgb=pow(gl_FragColor.rgb,vec3(GammaEncodePowerApprox));}}\n";class ss{static ExpandRGBDTexture(e){const t=e._texture;if(!t||!e.isRGBD)return;const i=t.getEngine(),n=i.getCaps(),r=t.isReady;let s=!1;n.textureHalfFloatRender&&n.textureHalfFloatLinearFiltering?(s=!0,t.type=Ze.TEXTURETYPE_HALF_FLOAT):n.textureFloatRender&&n.textureFloatLinearFiltering&&(s=!0,t.type=Ze.TEXTURETYPE_FLOAT),s&&(t.isReady=!1,t._isRGBD=!1,t.invertY=!1);const a=async()=>{const n=i.isWebGPU,r=n?1:0;t.isReady=!1,this._ShaderImported||(this._ShaderImported=!0,n?await Promise.all([Promise.resolve().then((function(){return Eu})),Promise.resolve().then((function(){return Ru}))]):await Promise.all([Promise.resolve().then((function(){return Mu})),Promise.resolve().then((function(){return Ou}))]));const s=new Vr("rgbdDecode","rgbdDecode",null,null,1,null,Ze.TEXTURE_TRILINEAR_SAMPLINGMODE,i,!1,void 0,t.type,void 0,null,!1,void 0,r);s.externalTextureSamplerBinding=!0;const a=i.createRenderTargetTexture(t.width,{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:t.samplingMode,type:t.type,format:Ze.TEXTUREFORMAT_RGBA});s.onEffectCreatedObservable.addOnce((n=>{n.executeWhenCompiled((()=>{s.onApply=e=>{e._bindTexture("textureSampler",t),e.setFloat2("scale",1,1)},e.getScene().postProcessManager.directRender([s],a,!0),i.restoreDefaultFramebuffer(),i._releaseTexture(t),s&&s.dispose(),a._swapAndDie(t),t.isReady=!0}))}))};s&&(r?a():e.onLoadObservable.addOnce(a))}static EncodeTextureToRGBD(e,t,i=Ze.TEXTURETYPE_UNSIGNED_BYTE){return function(e,t,i,n,r,s,a,o){const l=t.getEngine();return t.isReady=!1,r=r??t.samplingMode,n=n??t.type,s=s??t.format,a=a??t.width,o=o??t.height,-1===n&&(n=Ze.TEXTURETYPE_UNSIGNED_BYTE),new Promise((c=>{const h=new Vr("postprocess",e,null,null,1,null,r,l,!1,void 0,n,void 0,null,!1,s);h.externalTextureSamplerBinding=!0;const d=l.createRenderTargetTexture({width:a,height:o},{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:r,type:n,format:s});h.onEffectCreatedObservable.addOnce((e=>{e.executeWhenCompiled((()=>{h.onApply=e=>{e._bindTexture("textureSampler",t),e.setFloat2("scale",1,1)},i.postProcessManager.directRender([h],d,!0),l.restoreDefaultFramebuffer(),l._releaseTexture(t),h&&h.dispose(),d._swapAndDie(t),t.type=n,t.format=Ze.TEXTUREFORMAT_RGBA,t.isReady=!0,c(t)}))}))}))}("rgbdEncode",e,t,i,Ze.TEXTURE_NEAREST_SAMPLINGMODE,Ze.TEXTUREFORMAT_RGBA)}}ss._ShaderImported=!1;let as=0;const os=e=>{if(!e.environmentBRDFTexture){const t=e.useDelayedTextureLoading;e.useDelayedTextureLoading=!1;const i=e._blockEntityCollection;e._blockEntityCollection=!1;const n=Pr.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"+as++,e,!0,!1,Pr.BILINEAR_SAMPLINGMODE);e._blockEntityCollection=i;const r=e.getEngine().getLoadedTexturesCache(),s=r.indexOf(n.getInternalTexture());-1!==s&&r.splice(s,1),n.isRGBD=!0,n.wrapU=Pr.CLAMP_ADDRESSMODE,n.wrapV=Pr.CLAMP_ADDRESSMODE,e.environmentBRDFTexture=n,e.useDelayedTextureLoading=t,ss.ExpandRGBDTexture(n);const a=e.getEngine().onContextRestoredObservable.add((()=>{n.isRGBD=!0;const t=e.onBeforeRenderObservable.add((()=>{n.isReady()&&(e.onBeforeRenderObservable.remove(t),ss.ExpandRGBDTexture(n))}))}));e.onDisposeObservable.add((()=>{e.getEngine().onContextRestoredObservable.remove(a)}))}return e.environmentBRDFTexture};class ls{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;t<this._keys.length;t++){const i=this._keys[t];if(this[i]!==e[i])return!1}return!0}cloneTo(e){this._keys.length!==e._keys.length&&(e._keys=this._keys.slice(0));for(let t=0;t<this._keys.length;t++){const i=this._keys[t];e[i]=this[i]}}reset(){this._keys.forEach((e=>this._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;t<this._keys.length;t++){const i=this._keys[t],n=this[i];switch(typeof n){case"number":case"string":e+="#define "+i+" "+n+"\n";break;default:n&&(e+="#define "+i+"\n")}}return e}}const cs=new RegExp("^([gimus]+)!");class hs{constructor(e){this._plugins=[],this._activePlugins=[],this._activePluginsForExtraEvents=[],this._material=e,this._scene=e.getScene(),this._engine=this._scene.getEngine()}_addPlugin(e){for(let t=0;t<this._plugins.length;++t)if(this._plugins[t].name===e.name)return!1;if(this._material._uniformBufferLayoutBuilt)throw`The plugin "${e.name}" can't be added to the material "${this._material.name}" because this material has already been used for rendering! Please add plugins to materials before any rendering with this material occurs.`;if(!e.isCompatible(this._material.shaderLanguage))throw`The plugin "${e.name}" can't be added to the material "${this._material.name}" because the plugin is not compatible with the shader language of the material.`;const t=e.getClassName();hs._MaterialPluginClassToMainDefine[t]||(hs._MaterialPluginClassToMainDefine[t]="MATERIALPLUGIN_"+ ++hs._MaterialPluginCounter),this._material._callbackPluginEventGeneric=(e,t)=>this._handlePluginEvent(e,t),this._plugins.push(e),this._plugins.sort(((e,t)=>e.priority-t.priority)),this._codeInjectionPoints={};const i={};i[hs._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;t<this._plugins.length;++t)if(this._plugins[t].name===e)return this._plugins[t];return null}_handlePluginEventIsReadyForSubMesh(e){let t=!0;for(const i of this._activePlugins)t=t&&i.isReadyForSubMesh(e.defines,this._scene,this._engine,e.subMesh);e.isReadyForSubMesh=t}_handlePluginEventPrepareDefinesBeforeAttributes(e){for(const t of this._activePlugins)t.prepareDefinesBeforeAttributes(e.defines,this._scene,e.mesh)}_handlePluginEventPrepareDefines(e){for(const t of this._activePlugins)t.prepareDefines(e.defines,this._scene,e.mesh)}_handlePluginEventHardBindForSubMesh(e){for(const t of this._activePluginsForExtraEvents)t.hardBindForSubMesh(this._material._uniformBuffer,this._scene,this._engine,e.subMesh)}_handlePluginEventBindForSubMesh(e){for(const t of this._activePlugins)t.bindForSubMesh(this._material._uniformBuffer,this._scene,this._engine,e.subMesh)}_handlePluginEventHasRenderTargetTextures(e){let t=!1;for(const e of this._activePluginsForExtraEvents)if(t=e.hasRenderTargetTextures(),t)break;e.hasRenderTargetTextures=t}_handlePluginEventFillRenderTargetTextures(e){for(const t of this._activePluginsForExtraEvents)t.fillRenderTargetTextures(e.renderTargets)}_handlePluginEvent(e,t){switch(e){case 512:{const e=t;for(const t of this._activePlugins)t.getActiveTextures(e.activeTextures);break}case 256:{const e=t;for(const t of this._activePlugins)t.getAnimatables(e.animatables);break}case 1024:{const e=t;let i=!1;for(const t of this._activePlugins)if(i=t.hasTexture(e.texture),i)break;e.hasTexture=i;break}case 2:{const e=t;for(const t of this._plugins)t.dispose(e.forceDisposeTextures);break}case 4:t.defineNames=this._defineNamesFromPlugins;break;case 128:{const e=t;for(const t of this._activePlugins)e.fallbackRank=t.addFallbacks(e.defines,e.fallbacks,e.fallbackRank),t.getAttributes(e.attributes,this._scene,e.mesh);this._uniformList.length>0&&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 n=t.getUniforms(this._material.shaderLanguage);if(n){if(n.ubo)for(const t of n.ubo){if(t.size&&t.type){const n=t.arraySize??0;if(e.ubo.addUniform(t.name,t.size,n),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}${n>0?`[${n}]`:""};\n`}else this._uboDeclaration+=`${t.type} ${t.name}${n>0?`[${n}]`:""};\n`}this._uniformList.push(t.name)}n.vertex&&(this._vertexDeclaration+=n.vertex+"\n"),n.fragment&&(this._fragmentDeclaration+=n.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,n)=>{t&&(n=t(i,n)),this._uboDeclaration&&(n=n.replace("#define ADDITIONAL_UBO_DECLARATION",this._uboDeclaration)),this._vertexDeclaration&&(n=n.replace("#define ADDITIONAL_VERTEX_DECLARATION",this._vertexDeclaration)),this._fragmentDeclaration&&(n=n.replace("#define ADDITIONAL_FRAGMENT_DECLARATION",this._fragmentDeclaration));const r=this._codeInjectionPoints?.[i];if(!r)return n;let s=null;for(let t in r){let r="";for(const n of this._activePlugins){let a=n.getCustomCode(i,this._material.shaderLanguage)?.[t];if(a){if(n.resolveIncludes){if(null===s){const t=0;s={defines:[],indexParameters:e.indexParameters,isFragment:!1,shouldUseHighPrecisionShader:this._engine._shouldUseHighPrecisionShader,processor:void 0,supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:Je.GetShadersRepository(t),includesShadersStore:Je.GetIncludesShadersStore(t),version:void 0,platformName:this._engine.shaderPlatformName,processingContext:void 0,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer,processCodeAfterIncludes:void 0}}s.isFragment="fragment"===i,qe(a,s,(e=>a=e))}r+=a+"\n"}}if(r.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=cs.exec(t);i&&i.length>=2&&(e=i[1],t=t.substring(e.length+1))}e.indexOf("g")<0&&(e+="g");const i=n,s=new RegExp(t,e);let a=s.exec(i);for(;null!==a;){let e=r;for(let t=0;t<a.length;++t)e=e.replace("$"+t,a[t]);n=n.replace(a[0],e),a=s.exec(i)}}else{const e="#define "+t;n=n.replace(e,"\n"+r+"\n"+e)}}return n}}}hs._MaterialPluginClassToMainDefine={},hs._MaterialPluginCounter=0,y.OnEnginesDisposedObservable.add((()=>{ds.length=0,Ji.OnEventObservable.remove(us),us=null}));const ds=[];let us=null;class fs{isCompatible(e){return 0===e}_enable(e){e&&this._pluginManager._activatePlugin(this)}constructor(e,t,i,n,r=!0,s=!1,a=!1){this.priority=500,this.resolveIncludes=!1,this.registerForExtraEvents=!1,this._material=e,this.name=t,this.priority=i,this.resolveIncludes=a,e.pluginManager||(e.pluginManager=new hs(e),e.onDisposeObservable.add((()=>{e.pluginManager=void 0}))),this._pluginDefineNames=n,this._pluginManager=e.pluginManager,r&&this._pluginManager._addPlugin(this),s&&this._enable(!0),this.markAllDefinesAsDirty=e._dirtyCallbacks[Ze.MATERIAL_AllDirtyFlag]}getClassName(){return"MaterialPluginBase"}isReadyForSubMesh(e,t,i,n){return!0}hardBindForSubMesh(e,t,i,n){}bindForSubMesh(e,t,i,n){}dispose(e){}getCustomCode(e,t=0){return null}collectDefines(e){if(this._pluginDefineNames)for(const t of Object.keys(this._pluginDefineNames)){if("_"===t[0])continue;const i=typeof this._pluginDefineNames[t];e[t]={type:"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){re.Clone((()=>e),this)}serialize(){return re.Serialize(this)}parse(e,t,i){re.Parse((()=>this),e,t,i)}}e([a()],fs.prototype,"name",void 0),e([a()],fs.prototype,"priority",void 0),e([a()],fs.prototype,"resolveIncludes",void 0),e([a()],fs.prototype,"registerForExtraEvents",void 0),M("BABYLON.MaterialPluginBase",fs);class _s extends ls{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 ms extends fs{_markAllSubMeshesAsMiscDirty(){this._internalMarkAllSubMeshesAsMiscDirty()}isCompatible(){return!0}constructor(e,t=!0){super(e,"PBRBRDF",90,new _s,t),this._useEnergyConservation=ms.DEFAULT_USE_ENERGY_CONSERVATION,this.useEnergyConservation=ms.DEFAULT_USE_ENERGY_CONSERVATION,this._useSmithVisibilityHeightCorrelated=ms.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this.useSmithVisibilityHeightCorrelated=ms.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this._useSphericalHarmonics=ms.DEFAULT_USE_SPHERICAL_HARMONICS,this.useSphericalHarmonics=ms.DEFAULT_USE_SPHERICAL_HARMONICS,this._useSpecularGlossinessInputEnergyConservation=ms.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION,this.useSpecularGlossinessInputEnergyConservation=ms.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION,this._internalMarkAllSubMeshesAsMiscDirty=e._dirtyCallbacks[Ze.MATERIAL_MiscDirtyFlag],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"}}ms.DEFAULT_USE_ENERGY_CONSERVATION=!0,ms.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED=!0,ms.DEFAULT_USE_SPHERICAL_HARMONICS=!0,ms.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION=!0,e([a(),s("_markAllSubMeshesAsMiscDirty")],ms.prototype,"useEnergyConservation",void 0),e([a(),s("_markAllSubMeshesAsMiscDirty")],ms.prototype,"useSmithVisibilityHeightCorrelated",void 0),e([a(),s("_markAllSubMeshesAsMiscDirty")],ms.prototype,"useSphericalHarmonics",void 0),e([a(),s("_markAllSubMeshesAsMiscDirty")],ms.prototype,"useSpecularGlossinessInputEnergyConservation",void 0);class ps{constructor(){this.previousWorldMatrices={},this.previousBones={}}static AddUniforms(e){e.push("previousWorld","previousViewProjection","mPreviousBones")}static AddSamplers(e){}bindForSubMesh(e,t,i,n,r){if(t.prePassRenderer&&t.prePassRenderer.enabled&&t.prePassRenderer.currentRTisSceneRT&&-1!==t.prePassRenderer.getIndex(Ze.PREPASS_VELOCITY_TEXTURE_TYPE)){this.previousWorldMatrices[i.uniqueId]||(this.previousWorldMatrices[i.uniqueId]=n.clone()),this.previousViewProjection||(this.previousViewProjection=t.getTransformMatrix().clone(),this.currentViewProjection=t.getTransformMatrix().clone());const r=t.getEngine();this.currentViewProjection.updateFlag!==t.getTransformMatrix().updateFlag?(this._lastUpdateFrameId=r.frameId,this.previousViewProjection.copyFrom(this.currentViewProjection),this.currentViewProjection.copyFrom(t.getTransformMatrix())):this._lastUpdateFrameId!==r.frameId&&(this._lastUpdateFrameId=r.frameId,this.previousViewProjection.copyFrom(this.currentViewProjection)),e.setMatrix("previousWorld",this.previousWorldMatrices[i.uniqueId]),e.setMatrix("previousViewProjection",this.previousViewProjection),this.previousWorldMatrices[i.uniqueId]=n.clone()}}}class gs extends Ji{constructor(e,t,i=!0){super(e,t),this._normalMatrix=new k,this._storeEffectOnSubMeshes=i}getEffect(){return this._storeEffectOnSubMeshes?this._activeEffect:super.getEffect()}isReady(e,t){return!!e&&(!this._storeEffectOnSubMeshes||(!e.subMeshes||0===e.subMeshes.length||this.isReadyForSubMesh(e,e.subMeshes[0],t)))}_isReadyForSubMesh(e){const t=e.materialDefines;return!(this.checkReadyOnEveryCall||!e.effect||!t||t._renderId!==this.getScene().getRenderId())}bindOnlyWorldMatrix(e){this._activeEffect.setMatrix("world",e)}bindOnlyNormalMatrix(e){this._activeEffect.setMatrix("normalMatrix",e)}bind(e,t){t&&this.bindForSubMesh(e,t,t.subMeshes[0])}_afterBind(e,t=null,i){super._afterBind(e,t,i),this.getScene()._cachedEffect=t,i?i._drawWrapper._forceRebindOnNextCall=!1:this._drawWrapper._forceRebindOnNextCall=!1}_mustRebind(e,t,i,n=1){return i._drawWrapper._forceRebindOnNextCall||e.isCachedMaterialInvalid(this,t,n)}dispose(e,t,i){this._activeEffect=void 0,super.dispose(e,t,i)}}class Es{static get DiffuseTextureEnabled(){return this._DiffuseTextureEnabled}static set DiffuseTextureEnabled(e){this._DiffuseTextureEnabled!==e&&(this._DiffuseTextureEnabled=e,vt.MarkAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag))}static get DetailTextureEnabled(){return this._DetailTextureEnabled}static set DetailTextureEnabled(e){this._DetailTextureEnabled!==e&&(this._DetailTextureEnabled=e,vt.MarkAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag))}static get DecalMapEnabled(){return this._DecalMapEnabled}static set DecalMapEnabled(e){this._DecalMapEnabled!==e&&(this._DecalMapEnabled=e,vt.MarkAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag))}static get AmbientTextureEnabled(){return this._AmbientTextureEnabled}static set AmbientTextureEnabled(e){this._AmbientTextureEnabled!==e&&(this._AmbientTextureEnabled=e,vt.MarkAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag))}static get OpacityTextureEnabled(){return this._OpacityTextureEnabled}static set OpacityTextureEnabled(e){this._OpacityTextureEnabled!==e&&(this._OpacityTextureEnabled=e,vt.MarkAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag))}static get ReflectionTextureEnabled(){return this._ReflectionTextureEnabled}static set ReflectionTextureEnabled(e){this._ReflectionTextureEnabled!==e&&(this._ReflectionTextureEnabled=e,vt.MarkAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag))}static get EmissiveTextureEnabled(){return this._EmissiveTextureEnabled}static set EmissiveTextureEnabled(e){this._EmissiveTextureEnabled!==e&&(this._EmissiveTextureEnabled=e,vt.MarkAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag))}static get SpecularTextureEnabled(){return this._SpecularTextureEnabled}static set SpecularTextureEnabled(e){this._SpecularTextureEnabled!==e&&(this._SpecularTextureEnabled=e,vt.MarkAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag))}static get BumpTextureEnabled(){return this._BumpTextureEnabled}static set BumpTextureEnabled(e){this._BumpTextureEnabled!==e&&(this._BumpTextureEnabled=e,vt.MarkAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag))}static get LightmapTextureEnabled(){return this._LightmapTextureEnabled}static set LightmapTextureEnabled(e){this._LightmapTextureEnabled!==e&&(this._LightmapTextureEnabled=e,vt.MarkAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag))}static get RefractionTextureEnabled(){return this._RefractionTextureEnabled}static set RefractionTextureEnabled(e){this._RefractionTextureEnabled!==e&&(this._RefractionTextureEnabled=e,vt.MarkAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag))}static get ColorGradingTextureEnabled(){return this._ColorGradingTextureEnabled}static set ColorGradingTextureEnabled(e){this._ColorGradingTextureEnabled!==e&&(this._ColorGradingTextureEnabled=e,vt.MarkAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag))}static get FresnelEnabled(){return this._FresnelEnabled}static set FresnelEnabled(e){this._FresnelEnabled!==e&&(this._FresnelEnabled=e,vt.MarkAllMaterialsAsDirty(Ze.MATERIAL_FresnelDirtyFlag))}static get ClearCoatTextureEnabled(){return this._ClearCoatTextureEnabled}static set ClearCoatTextureEnabled(e){this._ClearCoatTextureEnabled!==e&&(this._ClearCoatTextureEnabled=e,vt.MarkAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag))}static get ClearCoatBumpTextureEnabled(){return this._ClearCoatBumpTextureEnabled}static set ClearCoatBumpTextureEnabled(e){this._ClearCoatBumpTextureEnabled!==e&&(this._ClearCoatBumpTextureEnabled=e,vt.MarkAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag))}static get ClearCoatTintTextureEnabled(){return this._ClearCoatTintTextureEnabled}static set ClearCoatTintTextureEnabled(e){this._ClearCoatTintTextureEnabled!==e&&(this._ClearCoatTintTextureEnabled=e,vt.MarkAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag))}static get SheenTextureEnabled(){return this._SheenTextureEnabled}static set SheenTextureEnabled(e){this._SheenTextureEnabled!==e&&(this._SheenTextureEnabled=e,vt.MarkAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag))}static get AnisotropicTextureEnabled(){return this._AnisotropicTextureEnabled}static set AnisotropicTextureEnabled(e){this._AnisotropicTextureEnabled!==e&&(this._AnisotropicTextureEnabled=e,vt.MarkAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag))}static get ThicknessTextureEnabled(){return this._ThicknessTextureEnabled}static set ThicknessTextureEnabled(e){this._ThicknessTextureEnabled!==e&&(this._ThicknessTextureEnabled=e,vt.MarkAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag))}static get RefractionIntensityTextureEnabled(){return this._ThicknessTextureEnabled}static set RefractionIntensityTextureEnabled(e){this._RefractionIntensityTextureEnabled!==e&&(this._RefractionIntensityTextureEnabled=e,vt.MarkAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag))}static get TranslucencyIntensityTextureEnabled(){return this._TranslucencyIntensityTextureEnabled}static set TranslucencyIntensityTextureEnabled(e){this._TranslucencyIntensityTextureEnabled!==e&&(this._TranslucencyIntensityTextureEnabled=e,vt.MarkAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag))}static get TranslucencyColorTextureEnabled(){return this._TranslucencyColorTextureEnabled}static set TranslucencyColorTextureEnabled(e){this._TranslucencyColorTextureEnabled!==e&&(this._TranslucencyColorTextureEnabled=e,vt.MarkAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag))}static get IridescenceTextureEnabled(){return this._IridescenceTextureEnabled}static set IridescenceTextureEnabled(e){this._IridescenceTextureEnabled!==e&&(this._IridescenceTextureEnabled=e,vt.MarkAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag))}}Es._DiffuseTextureEnabled=!0,Es._DetailTextureEnabled=!0,Es._DecalMapEnabled=!0,Es._AmbientTextureEnabled=!0,Es._OpacityTextureEnabled=!0,Es._ReflectionTextureEnabled=!0,Es._EmissiveTextureEnabled=!0,Es._SpecularTextureEnabled=!0,Es._BumpTextureEnabled=!0,Es._LightmapTextureEnabled=!0,Es._RefractionTextureEnabled=!0,Es._ColorGradingTextureEnabled=!0,Es._FresnelEnabled=!0,Es._ClearCoatTextureEnabled=!0,Es._ClearCoatBumpTextureEnabled=!0,Es._ClearCoatTintTextureEnabled=!0,Es._SheenTextureEnabled=!0,Es._AnisotropicTextureEnabled=!0,Es._ThicknessTextureEnabled=!0,Es._RefractionIntensityTextureEnabled=!0,Es._TranslucencyIntensityTextureEnabled=!0,Es._TranslucencyColorTextureEnabled=!0,Es._IridescenceTextureEnabled=!0;const Ts=[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))],As=[()=>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],vs=(e,t)=>Ts[e]*As[e](t),Rs=[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 Ss{constructor(){this.preScaled=!1,this.l00=B.Zero(),this.l1_1=B.Zero(),this.l10=B.Zero(),this.l11=B.Zero(),this.l2_2=B.Zero(),this.l2_1=B.Zero(),this.l20=B.Zero(),this.l21=B.Zero(),this.l22=B.Zero()}addLight(e,t,i){H.Vector3[0].set(t.r,t.g,t.b);const n=H.Vector3[0],r=H.Vector3[1];n.scaleToRef(i,r),r.scaleToRef(vs(0,e),H.Vector3[2]),this.l00.addInPlace(H.Vector3[2]),r.scaleToRef(vs(1,e),H.Vector3[2]),this.l1_1.addInPlace(H.Vector3[2]),r.scaleToRef(vs(2,e),H.Vector3[2]),this.l10.addInPlace(H.Vector3[2]),r.scaleToRef(vs(3,e),H.Vector3[2]),this.l11.addInPlace(H.Vector3[2]),r.scaleToRef(vs(4,e),H.Vector3[2]),this.l2_2.addInPlace(H.Vector3[2]),r.scaleToRef(vs(5,e),H.Vector3[2]),this.l2_1.addInPlace(H.Vector3[2]),r.scaleToRef(vs(6,e),H.Vector3[2]),this.l20.addInPlace(H.Vector3[2]),r.scaleToRef(vs(7,e),H.Vector3[2]),this.l21.addInPlace(H.Vector3[2]),r.scaleToRef(vs(8,e),H.Vector3[2]),this.l22.addInPlace(H.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(Rs[0]),this.l1_1.scaleInPlace(Rs[1]),this.l10.scaleInPlace(Rs[2]),this.l11.scaleInPlace(Rs[3]),this.l2_2.scaleInPlace(Rs[4]),this.l2_1.scaleInPlace(Rs[5]),this.l20.scaleInPlace(Rs[6]),this.l21.scaleInPlace(Rs[7]),this.l22.scaleInPlace(Rs[8])}convertIrradianceToLambertianRadiance(){this.scaleInPlace(1/Math.PI)}preScaleForRendering(){this.preScaled=!0,this.l00.scaleInPlace(Ts[0]),this.l1_1.scaleInPlace(Ts[1]),this.l10.scaleInPlace(Ts[2]),this.l11.scaleInPlace(Ts[3]),this.l2_2.scaleInPlace(Ts[4]),this.l2_1.scaleInPlace(Ts[5]),this.l20.scaleInPlace(Ts[6]),this.l21.scaleInPlace(Ts[7]),this.l22.scaleInPlace(Ts[8])}updateFromArray(e){return B.FromArrayToRef(e[0],0,this.l00),B.FromArrayToRef(e[1],0,this.l1_1),B.FromArrayToRef(e[2],0,this.l10),B.FromArrayToRef(e[3],0,this.l11),B.FromArrayToRef(e[4],0,this.l2_2),B.FromArrayToRef(e[5],0,this.l2_1),B.FromArrayToRef(e[6],0,this.l20),B.FromArrayToRef(e[7],0,this.l21),B.FromArrayToRef(e[8],0,this.l22),this}updateFromFloatsArray(e){return B.FromFloatsToRef(e[0],e[1],e[2],this.l00),B.FromFloatsToRef(e[3],e[4],e[5],this.l1_1),B.FromFloatsToRef(e[6],e[7],e[8],this.l10),B.FromFloatsToRef(e[9],e[10],e[11],this.l11),B.FromFloatsToRef(e[12],e[13],e[14],this.l2_2),B.FromFloatsToRef(e[15],e[16],e[17],this.l2_1),B.FromFloatsToRef(e[18],e[19],e[20],this.l20),B.FromFloatsToRef(e[21],e[22],e[23],this.l21),B.FromFloatsToRef(e[24],e[25],e[26],this.l22),this}static FromArray(e){return(new Ss).updateFromArray(e)}static FromPolynomial(e){const t=new Ss;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 Is{constructor(){this.x=B.Zero(),this.y=B.Zero(),this.z=B.Zero(),this.xx=B.Zero(),this.yy=B.Zero(),this.zz=B.Zero(),this.xy=B.Zero(),this.yz=B.Zero(),this.zx=B.Zero()}get preScaledHarmonics(){return this._harmonics||(this._harmonics=Ss.FromPolynomial(this)),this._harmonics.preScaled||this._harmonics.preScaleForRendering(),this._harmonics}addAmbient(e){H.Vector3[0].copyFromFloats(e.r,e.g,e.b);const t=H.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),H.Vector3[0].copyFrom(e.l20).scaleInPlace(.247708),H.Vector3[1].copyFrom(e.l22).scaleInPlace(.429043),this.xx.scaleInPlace(.886277).subtractInPlace(H.Vector3[0]).addInPlace(H.Vector3[1]),this.yy.copyFrom(e.l00),this.yy.scaleInPlace(.886277).subtractInPlace(H.Vector3[0]).subtractInPlace(H.Vector3[1]),this.zz.copyFrom(e.l00),H.Vector3[0].copyFrom(e.l20).scaleInPlace(.495417),this.zz.scaleInPlace(.886277).addInPlace(H.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 Is).updateFromHarmonics(e)}static FromArray(e){const t=new Is;return B.FromArrayToRef(e[0],0,t.x),B.FromArrayToRef(e[1],0,t.y),B.FromArrayToRef(e[2],0,t.z),B.FromArrayToRef(e[3],0,t.xx),B.FromArrayToRef(e[4],0,t.yy),B.FromArrayToRef(e[5],0,t.zz),B.FromArrayToRef(e[6],0,t.yz),B.FromArrayToRef(e[7],0,t.zx),B.FromArrayToRef(e[8],0,t.xy),t}}class Cs{constructor(e,t,i,n){this.name=e,this.worldAxisForNormal=t,this.worldAxisForFileX=i,this.worldAxisForFileY=n}}class Ms{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),n=e.readPixels(1,void 0,void 0,!1);let r,s;e.isRenderTarget?(r=e.readPixels(3,void 0,void 0,!1),s=e.readPixels(2,void 0,void 0,!1)):(r=e.readPixels(2,void 0,void 0,!1),s=e.readPixels(3,void 0,void 0,!1));const a=e.readPixels(4,void 0,void 0,!1),o=e.readPixels(5,void 0,void 0,!1),l=e.gammaSpace,c=Ze.TEXTUREFORMAT_RGBA;let h=Ze.TEXTURETYPE_UNSIGNED_INT;return e.textureType!=Ze.TEXTURETYPE_FLOAT&&e.textureType!=Ze.TEXTURETYPE_HALF_FLOAT||(h=Ze.TEXTURETYPE_FLOAT),new Promise((e=>{Promise.all([n,i,r,s,a,o]).then((([i,n,r,s,a,o])=>{const d={size:t,right:n,left:i,up:r,down:s,front:a,back:o,format:c,type:h,gammaSpace:l};e(this.ConvertCubeMapToSphericalPolynomial(d))}))}))}static _AreaElement(e,t){return Math.atan2(e*t,Math.sqrt(e*e+t*t+1))}static ConvertCubeMapToSphericalPolynomial(e){const t=new Ss;let i=0;const n=2/e.size,r=n,s=.5*n,a=s-1;for(let o=0;o<6;o++){const l=this._FileFaces[o],c=e[l.name];let h=a;const d=e.format===Ze.TEXTUREFORMAT_RGBA?4:3;for(let o=0;o<e.size;o++){let u=a;for(let r=0;r<e.size;r++){const a=l.worldAxisForFileX.scale(u).add(l.worldAxisForFileY.scale(h)).add(l.worldAxisForNormal);a.normalize();const f=this._AreaElement(u-s,h-s)-this._AreaElement(u-s,h+s)-this._AreaElement(u+s,h-s)+this._AreaElement(u+s,h+s);let _=c[o*e.size*d+r*d+0],m=c[o*e.size*d+r*d+1],p=c[o*e.size*d+r*d+2];isNaN(_)&&(_=0),isNaN(m)&&(m=0),isNaN(p)&&(p=0),e.type===Ze.TEXTURETYPE_UNSIGNED_INT&&(_/=255,m/=255,p/=255),e.gammaSpace&&(_=Math.pow(j.Clamp(_),T),m=Math.pow(j.Clamp(m),T),p=Math.pow(j.Clamp(p),T));const g=this.MAX_HDRI_VALUE;if(this.PRESERVE_CLAMPED_COLORS){const e=Math.max(_,m,p);if(e>g){const t=g/e;_*=t,m*=t,p*=t}}else _=j.Clamp(_,0,g),m=j.Clamp(m,0,g),p=j.Clamp(p,0,g);const E=new ee(_,m,p);t.addLight(a,E,f),i+=f,u+=n}h+=r}}const o=6*(4*Math.PI)/6/i;return t.scaleInPlace(o),t.convertIncidentRadianceToIrradiance(),t.convertIrradianceToLambertianRadiance(),Is.FromHarmonics(t)}}Ms._FileFaces=[new Cs("right",new B(1,0,0),new B(0,0,-1),new B(0,-1,0)),new Cs("left",new B(-1,0,0),new B(0,0,1),new B(0,-1,0)),new Cs("up",new B(0,1,0),new B(1,0,0),new B(0,0,1)),new Cs("down",new B(0,-1,0),new B(1,0,0),new B(0,0,-1)),new Cs("front",new B(0,0,1),new B(1,0,0),new B(0,-1,0)),new Cs("back",new B(0,0,-1),new B(-1,0,0),new B(0,-1,0))],Ms.MAX_HDRI_VALUE=4096,Ms.PRESERVE_CLAMPED_COLORS=!1,Dr.prototype.forceSphericalPolynomialsRecompute=function(){this._texture&&(this._texture._sphericalPolynomial=null,this._texture._sphericalPolynomialPromise=null,this._texture._sphericalPolynomialComputed=!1)},Object.defineProperty(Dr.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=Ms.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});class xs{constructor(){this._defines={},this._currentRank=32,this._maxRank=-1,this._mesh=null}unBindMesh(){this._mesh=null}addFallback(e,t){this._defines[e]||(e<this._currentRank&&(this._currentRank=e),e>this._maxRank&&(this._maxRank=e),this._defines[e]=new Array),this._defines[e].push(t)}addCPUSkinningFallback(e,t){this._mesh=t,e<this._currentRank&&(this._currentRank=e),e>this._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;e<i.meshes.length;e++){const n=i.meshes[e];if(n.material){if(n.computeBonesUsingShaders&&0!==n.numBoneInfluencers)if(n.material.getEffect()===t)n.computeBonesUsingShaders=!1;else if(n.subMeshes)for(const e of n.subMeshes){if(e.effect===t){n.computeBonesUsingShaders=!1;break}}}else!this._mesh.material&&n.computeBonesUsingShaders&&n.numBoneInfluencers>0&&(n.computeBonesUsingShaders=!1)}}else{const t=this._defines[this._currentRank];if(t)for(let i=0;i<t.length;i++)e=e.replace("#define "+t[i],"");this._currentRank++}return e}}class bs extends ls{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 ys extends fs{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}isCompatible(){return!0}constructor(e,t=!0){super(e,"PBRClearCoat",100,new bs,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.roughness=0,this._indexOfRefraction=ys._DefaultIndexOfRefraction,this.indexOfRefraction=ys._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=ee.White(),this.tintColorAtDistance=1,this.tintThickness=1,this._tintTexture=null,this.tintTexture=null,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[Ze.MATERIAL_TextureDirtyFlag]}isReadyForSubMesh(e,t,i){if(!this._isEnabled)return!0;const n=this._material._disableBumpMap;if(e._areTexturesDirty&&t.texturesEnabled){if(this._texture&&Es.ClearCoatTextureEnabled&&!this._texture.isReadyOrNotBlocking())return!1;if(this._textureRoughness&&Es.ClearCoatTextureEnabled&&!this._textureRoughness.isReadyOrNotBlocking())return!1;if(i.getCaps().standardDerivatives&&this._bumpTexture&&Es.ClearCoatBumpTextureEnabled&&!n&&!this._bumpTexture.isReady())return!1;if(this._isTintEnabled&&this._tintTexture&&Es.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&&Es.ClearCoatTextureEnabled?zi(this._texture,e,"CLEARCOAT_TEXTURE"):e.CLEARCOAT_TEXTURE=!1,this._textureRoughness&&Es.ClearCoatTextureEnabled?zi(this._textureRoughness,e,"CLEARCOAT_TEXTURE_ROUGHNESS"):e.CLEARCOAT_TEXTURE_ROUGHNESS=!1,this._bumpTexture&&Es.ClearCoatBumpTextureEnabled?zi(this._bumpTexture,e,"CLEARCOAT_BUMP"):e.CLEARCOAT_BUMP=!1,e.CLEARCOAT_DEFAULTIOR=this._indexOfRefraction===ys._DefaultIndexOfRefraction,this._isTintEnabled?(e.CLEARCOAT_TINT=!0,this._tintTexture&&Es.ClearCoatTintTextureEnabled?(zi(this._tintTexture,e,"CLEARCOAT_TINT_TEXTURE"),e.CLEARCOAT_TINT_GAMMATEXTURE=this._tintTexture.gammaSpace):e.CLEARCOAT_TINT_TEXTURE=!1):(e.CLEARCOAT_TINT=!1,e.CLEARCOAT_TINT_TEXTURE=!1))):(e.CLEARCOAT=!1,e.CLEARCOAT_TEXTURE=!1,e.CLEARCOAT_TEXTURE_ROUGHNESS=!1,e.CLEARCOAT_BUMP=!1,e.CLEARCOAT_TINT=!1,e.CLEARCOAT_TINT_TEXTURE=!1,e.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE=!1,e.CLEARCOAT_DEFAULTIOR=!1,e.CLEARCOAT_TEXTUREDIRECTUV=0,e.CLEARCOAT_TEXTURE_ROUGHNESSDIRECTUV=0,e.CLEARCOAT_BUMPDIRECTUV=0,e.CLEARCOAT_REMAP_F0=!1,e.CLEARCOAT_TINT_TEXTUREDIRECTUV=0,e.CLEARCOAT_TINT_GAMMATEXTURE=!1)}bindForSubMesh(e,t,i,n){if(!this._isEnabled)return;const r=n.materialDefines,s=this._material.isFrozen,a=this._material._disableBumpMap,o=this._material._invertNormalMapX,l=this._material._invertNormalMapY;if(!e.useUbo||!s||!e.isSync){(this._texture||this._textureRoughness)&&Es.ClearCoatTextureEnabled&&(e.updateFloat4("vClearCoatInfos",this._texture?.coordinatesIndex??0,this._texture?.level??0,this._textureRoughness?.coordinatesIndex??0,this._textureRoughness?.level??0),this._texture&&Yi(this._texture,e,"clearCoat"),this._textureRoughness&&!r.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE&&Yi(this._textureRoughness,e,"clearCoatRoughness")),this._bumpTexture&&i.getCaps().standardDerivatives&&Es.ClearCoatTextureEnabled&&!a&&(e.updateFloat2("vClearCoatBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level),Yi(this._bumpTexture,e,"clearCoatBump"),t._mirroredCameraPosition?e.updateFloat2("vClearCoatTangentSpaceParams",o?1:-1,l?1:-1):e.updateFloat2("vClearCoatTangentSpaceParams",o?-1:1,l?-1:1)),this._tintTexture&&Es.ClearCoatTintTextureEnabled&&(e.updateFloat2("vClearCoatTintInfos",this._tintTexture.coordinatesIndex,this._tintTexture.level),Yi(this._tintTexture,e,"clearCoatTint")),e.updateFloat2("vClearCoatParams",this.intensity,this.roughness);const n=1-this._indexOfRefraction,s=1+this._indexOfRefraction,c=Math.pow(-n/s,2),h=1/this._indexOfRefraction;e.updateFloat4("vClearCoatRefractionParams",c,h,n,s),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&&Es.ClearCoatTextureEnabled&&e.setTexture("clearCoatSampler",this._texture),this._textureRoughness&&!r.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE&&Es.ClearCoatTextureEnabled&&e.setTexture("clearCoatRoughnessSampler",this._textureRoughness),this._bumpTexture&&i.getCaps().standardDerivatives&&Es.ClearCoatBumpTextureEnabled&&!a&&e.setTexture("clearCoatBumpSampler",this._bumpTexture),this._isTintEnabled&&this._tintTexture&&Es.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"}]}}}ys._DefaultIndexOfRefraction=1.5,e([a(),s("_markAllSubMeshesAsTexturesDirty")],ys.prototype,"isEnabled",void 0),e([a()],ys.prototype,"intensity",void 0),e([a()],ys.prototype,"roughness",void 0),e([a(),s("_markAllSubMeshesAsTexturesDirty")],ys.prototype,"indexOfRefraction",void 0),e([o(),s("_markAllSubMeshesAsTexturesDirty")],ys.prototype,"texture",void 0),e([a(),s("_markAllSubMeshesAsTexturesDirty")],ys.prototype,"useRoughnessFromMainTexture",void 0),e([o(),s("_markAllSubMeshesAsTexturesDirty")],ys.prototype,"textureRoughness",void 0),e([a(),s("_markAllSubMeshesAsTexturesDirty")],ys.prototype,"remapF0OnInterfaceChange",void 0),e([o(),s("_markAllSubMeshesAsTexturesDirty")],ys.prototype,"bumpTexture",void 0),e([a(),s("_markAllSubMeshesAsTexturesDirty")],ys.prototype,"isTintEnabled",void 0),e([l()],ys.prototype,"tintColor",void 0),e([a()],ys.prototype,"tintColorAtDistance",void 0),e([a()],ys.prototype,"tintThickness",void 0),e([o(),s("_markAllSubMeshesAsTexturesDirty")],ys.prototype,"tintTexture",void 0);class Os extends ls{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 Ds extends fs{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}isCompatible(){return!0}constructor(e,t=!0){super(e,"PBRIridescence",110,new Os,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.minimumThickness=Ds._DefaultMinimumThickness,this.maximumThickness=Ds._DefaultMaximumThickness,this.indexOfRefraction=Ds._DefaultIndexOfRefraction,this._texture=null,this.texture=null,this._thicknessTexture=null,this.thicknessTexture=null,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[Ze.MATERIAL_TextureDirtyFlag]}isReadyForSubMesh(e,t){if(!this._isEnabled)return!0;if(e._areTexturesDirty&&t.texturesEnabled){if(this._texture&&Es.IridescenceTextureEnabled&&!this._texture.isReadyOrNotBlocking())return!1;if(this._thicknessTexture&&Es.IridescenceTextureEnabled&&!this._thicknessTexture.isReadyOrNotBlocking())return!1}return!0}prepareDefinesBeforeAttributes(e,t){this._isEnabled?(e.IRIDESCENCE=!0,e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&Es.IridescenceTextureEnabled?zi(this._texture,e,"IRIDESCENCE_TEXTURE"):e.IRIDESCENCE_TEXTURE=!1,this._thicknessTexture&&Es.IridescenceTextureEnabled?zi(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)&&Es.IridescenceTextureEnabled&&(e.updateFloat4("vIridescenceInfos",this._texture?.coordinatesIndex??0,this._texture?.level??0,this._thicknessTexture?.coordinatesIndex??0,this._thicknessTexture?.level??0),this._texture&&Yi(this._texture,e,"iridescence"),this._thicknessTexture&&Yi(this._thicknessTexture,e,"iridescenceThickness")),e.updateFloat4("vIridescenceParams",this.intensity,this.indexOfRefraction,this.minimumThickness,this.maximumThickness)),t.texturesEnabled&&(this._texture&&Es.IridescenceTextureEnabled&&e.setTexture("iridescenceSampler",this._texture),this._thicknessTexture&&Es.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"}]}}}Ds._DefaultMinimumThickness=100,Ds._DefaultMaximumThickness=400,Ds._DefaultIndexOfRefraction=1.3,e([a(),s("_markAllSubMeshesAsTexturesDirty")],Ds.prototype,"isEnabled",void 0),e([a()],Ds.prototype,"intensity",void 0),e([a()],Ds.prototype,"minimumThickness",void 0),e([a()],Ds.prototype,"maximumThickness",void 0),e([a()],Ds.prototype,"indexOfRefraction",void 0),e([o(),s("_markAllSubMeshesAsTexturesDirty")],Ds.prototype,"texture",void 0),e([o(),s("_markAllSubMeshesAsTexturesDirty")],Ds.prototype,"thicknessTexture",void 0);class Ns extends ls{constructor(){super(...arguments),this.ANISOTROPIC=!1,this.ANISOTROPIC_TEXTURE=!1,this.ANISOTROPIC_TEXTUREDIRECTUV=0,this.ANISOTROPIC_LEGACY=!1,this.MAINUV1=!1}}class Ps extends fs{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 Ns,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.direction=new U(1,0),this._texture=null,this.texture=null,this._legacy=!1,this.legacy=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[Ze.MATERIAL_TextureDirtyFlag],this._internalMarkAllSubMeshesAsMiscDirty=e._dirtyCallbacks[Ze.MATERIAL_MiscDirtyFlag]}isReadyForSubMesh(e,t){return!this._isEnabled||!(e._areTexturesDirty&&t.texturesEnabled&&this._texture&&Es.AnisotropicTextureEnabled&&!this._texture.isReadyOrNotBlocking())}prepareDefinesBeforeAttributes(e,t,i){this._isEnabled?(e.ANISOTROPIC=this._isEnabled,this._isEnabled&&!i.isVerticesDataPresent(si.TangentKind)&&(e._needUVs=!0,e.MAINUV1=!0),e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&Es.AnisotropicTextureEnabled?zi(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&&Es.AnisotropicTextureEnabled&&(e.updateFloat2("vAnisotropyInfos",this._texture.coordinatesIndex,this._texture.level),Yi(this._texture,e,"anisotropy")),e.updateFloat3("vAnisotropy",this.direction.x,this.direction.y,this.intensity)),t.texturesEnabled&&this._texture&&Es.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)}}e([a(),s("_markAllSubMeshesAsTexturesDirty")],Ps.prototype,"isEnabled",void 0),e([a()],Ps.prototype,"intensity",void 0),e([c()],Ps.prototype,"direction",void 0),e([o(),s("_markAllSubMeshesAsTexturesDirty")],Ps.prototype,"texture",void 0),e([a(),s("_markAllSubMeshesAsMiscDirty")],Ps.prototype,"legacy",void 0);class Ls extends ls{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 Fs extends fs{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}isCompatible(){return!0}constructor(e,t=!0){super(e,"Sheen",120,new Ls,t),this._isEnabled=!1,this.isEnabled=!1,this._linkSheenWithAlbedo=!1,this.linkSheenWithAlbedo=!1,this.intensity=1,this.color=ee.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[Ze.MATERIAL_TextureDirtyFlag]}isReadyForSubMesh(e,t){if(!this._isEnabled)return!0;if(e._areTexturesDirty&&t.texturesEnabled){if(this._texture&&Es.SheenTextureEnabled&&!this._texture.isReadyOrNotBlocking())return!1;if(this._textureRoughness&&Es.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&&Es.SheenTextureEnabled?(zi(this._texture,e,"SHEEN_TEXTURE"),e.SHEEN_GAMMATEXTURE=this._texture.gammaSpace):e.SHEEN_TEXTURE=!1,this._textureRoughness&&Es.SheenTextureEnabled?zi(this._textureRoughness,e,"SHEEN_TEXTURE_ROUGHNESS"):e.SHEEN_TEXTURE_ROUGHNESS=!1)):(e.SHEEN=!1,e.SHEEN_TEXTURE=!1,e.SHEEN_TEXTURE_ROUGHNESS=!1,e.SHEEN_LINKWITHALBEDO=!1,e.SHEEN_ROUGHNESS=!1,e.SHEEN_ALBEDOSCALING=!1,e.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE=!1,e.SHEEN_GAMMATEXTURE=!1,e.SHEEN_TEXTUREDIRECTUV=0,e.SHEEN_TEXTURE_ROUGHNESSDIRECTUV=0)}bindForSubMesh(e,t,i,n){if(!this._isEnabled)return;const r=n.materialDefines,s=this._material.isFrozen;e.useUbo&&s&&e.isSync||((this._texture||this._textureRoughness)&&Es.SheenTextureEnabled&&(e.updateFloat4("vSheenInfos",this._texture?.coordinatesIndex??0,this._texture?.level??0,this._textureRoughness?.coordinatesIndex??0,this._textureRoughness?.level??0),this._texture&&Yi(this._texture,e,"sheen"),this._textureRoughness&&!r.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE&&Yi(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&&Es.SheenTextureEnabled&&e.setTexture("sheenSampler",this._texture),this._textureRoughness&&!r.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE&&Es.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"}]}}}e([a(),s("_markAllSubMeshesAsTexturesDirty")],Fs.prototype,"isEnabled",void 0),e([a(),s("_markAllSubMeshesAsTexturesDirty")],Fs.prototype,"linkSheenWithAlbedo",void 0),e([a()],Fs.prototype,"intensity",void 0),e([l()],Fs.prototype,"color",void 0),e([o(),s("_markAllSubMeshesAsTexturesDirty")],Fs.prototype,"texture",void 0),e([a(),s("_markAllSubMeshesAsTexturesDirty")],Fs.prototype,"useRoughnessFromMainTexture",void 0),e([a(),s("_markAllSubMeshesAsTexturesDirty")],Fs.prototype,"roughness",void 0),e([o(),s("_markAllSubMeshesAsTexturesDirty")],Fs.prototype,"textureRoughness",void 0),e([a(),s("_markAllSubMeshesAsTexturesDirty")],Fs.prototype,"albedoScaling",void 0);class ws extends ls{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 Us extends fs{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._internalMarkAllSubMeshesAsTexturesDirty(),this._internalMarkScenePrePassDirty()}isCompatible(){return!0}constructor(e,t=!0){super(e,"PBRSubSurface",130,new ws,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=ee.White(),this.tintColorAtDistance=1,this.dispersion=0,this.diffusionDistance=ee.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[Ze.MATERIAL_TextureDirtyFlag],this._internalMarkScenePrePassDirty=e._dirtyCallbacks[Ze.MATERIAL_PrePassDirtyFlag]}isReadyForSubMesh(e,t){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return!0;if(e._areTexturesDirty&&t.texturesEnabled){if(this._thicknessTexture&&Es.ThicknessTextureEnabled&&!this._thicknessTexture.isReadyOrNotBlocking())return!1;if(this._translucencyColorTexture&&Es.TranslucencyColorTextureEnabled&&!this._translucencyColorTexture.isReadyOrNotBlocking())return!1;if(this._translucencyIntensityTexture&&Es.TranslucencyIntensityTextureEnabled&&!this._translucencyIntensityTexture.isReadyOrNotBlocking())return!1;const e=this._getRefractionTexture(t);if(e&&Es.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&&Es.ThicknessTextureEnabled&&zi(this._thicknessTexture,e,"SS_THICKNESSANDMASK_TEXTURE"),this._refractionIntensityTexture&&Es.RefractionIntensityTextureEnabled&&zi(this._refractionIntensityTexture,e,"SS_REFRACTIONINTENSITY_TEXTURE"),this._translucencyIntensityTexture&&Es.TranslucencyIntensityTextureEnabled&&zi(this._translucencyIntensityTexture,e,"SS_TRANSLUCENCYINTENSITY_TEXTURE"),this._translucencyColorTexture&&Es.TranslucencyColorTextureEnabled&&zi(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&&Es.RefractionTextureEnabled&&(e.SS_REFRACTION=!0,e.SS_REFRACTIONMAP_3D=i.isCube,e.SS_GAMMAREFRACTION=i.gammaSpace,e.SS_RGBDREFRACTION=i.isRGBD,e.SS_LINEARSPECULARREFRACTION=i.linearSpecularLOD,e.SS_REFRACTIONMAP_OPPOSITEZ=this._scene.useRightHandedSystem&&i.isCube?!i.invertZ:i.invertZ,e.SS_LODINREFRACTIONALPHA=i.lodLevelInAlpha,e.SS_LINKREFRACTIONTOTRANSPARENCY=this._linkRefractionWithTransparency,e.SS_ALBEDOFORREFRACTIONTINT=this.useAlbedoToTintRefraction,e.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=i.isCube&&i.boundingBoxSize,e.SS_USE_THICKNESS_AS_DEPTH=this.useThicknessAsDepth)}this._isTranslucencyEnabled&&(e.SS_ALBEDOFORTRANSLUCENCYTINT=this.useAlbedoToTintTranslucency)}}hardBindForSubMesh(e,t,i,n){if(this._isRefractionEnabled||this._isTranslucencyEnabled||this._isScatteringEnabled)if(0===this.maximumThickness&&0===this.minimumThickness)e.updateFloat2("vThicknessParam",0,0);else{n.getRenderingMesh().getWorldMatrix().decompose(H.Vector3[0]);const t=Math.max(Math.abs(H.Vector3[0].x),Math.abs(H.Vector3[0].y),Math.abs(H.Vector3[0].z));e.updateFloat2("vThicknessParam",this.minimumThickness*t,(this.maximumThickness-this.minimumThickness)*t)}}bindForSubMesh(e,t,i,n){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return;const r=n.materialDefines,s=this._material.isFrozen,a=this._material.realTimeFiltering,o=r.LODBASEDMICROSFURACE,l=this._getRefractionTexture(t);if(!e.useUbo||!s||!e.isSync){if(this._thicknessTexture&&Es.ThicknessTextureEnabled&&(e.updateFloat2("vThicknessInfos",this._thicknessTexture.coordinatesIndex,this._thicknessTexture.level),Yi(this._thicknessTexture,e,"thickness")),this._refractionIntensityTexture&&Es.RefractionIntensityTextureEnabled&&r.SS_REFRACTIONINTENSITY_TEXTURE&&(e.updateFloat2("vRefractionIntensityInfos",this._refractionIntensityTexture.coordinatesIndex,this._refractionIntensityTexture.level),Yi(this._refractionIntensityTexture,e,"refractionIntensity")),this._translucencyColorTexture&&Es.TranslucencyColorTextureEnabled&&r.SS_TRANSLUCENCYCOLOR_TEXTURE&&(e.updateFloat2("vTranslucencyColorInfos",this._translucencyColorTexture.coordinatesIndex,this._translucencyColorTexture.level),Yi(this._translucencyColorTexture,e,"translucencyColor")),this._translucencyIntensityTexture&&Es.TranslucencyIntensityTextureEnabled&&r.SS_TRANSLUCENCYINTENSITY_TEXTURE&&(e.updateFloat2("vTranslucencyIntensityInfos",this._translucencyIntensityTexture.coordinatesIndex,this._translucencyIntensityTexture.level),Yi(this._translucencyIntensityTexture,e,"translucencyIntensity")),l&&Es.RefractionTextureEnabled){e.updateMatrix("refractionMatrix",l.getRefractionTextureMatrix());let t=1;l.isCube||l.depth&&(t=l.depth);const i=l.getSize().width,n=this.volumeIndexOfRefraction;if(e.updateFloat4("vRefractionInfos",l.level,1/n,t,this._invertRefractionY?-1:1),e.updateFloat4("vRefractionMicrosurfaceInfos",i,l.lodGenerationScale,l.lodGenerationOffset,1/this.indexOfRefraction),a&&e.updateFloat2("vRefractionFilteringInfo",i,j.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&&Es.ThicknessTextureEnabled&&e.setTexture("thicknessSampler",this._thicknessTexture),this._refractionIntensityTexture&&Es.RefractionIntensityTextureEnabled&&r.SS_REFRACTIONINTENSITY_TEXTURE&&e.setTexture("refractionIntensitySampler",this._refractionIntensityTexture),this._translucencyIntensityTexture&&Es.TranslucencyIntensityTextureEnabled&&r.SS_TRANSLUCENCYINTENSITY_TEXTURE&&e.setTexture("translucencyIntensitySampler",this._translucencyIntensityTexture),this._translucencyColorTexture&&Es.TranslucencyColorTextureEnabled&&r.SS_TRANSLUCENCYCOLOR_TEXTURE&&e.setTexture("translucencyColorSampler",this._translucencyColorTexture),l&&Es.RefractionTextureEnabled&&(o?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){Es.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!!(Es.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"}]}}}e([a(),s("_markAllSubMeshesAsTexturesDirty")],Us.prototype,"isRefractionEnabled",void 0),e([a(),s("_markAllSubMeshesAsTexturesDirty")],Us.prototype,"isTranslucencyEnabled",void 0),e([a(),s("_markAllSubMeshesAsTexturesDirty")],Us.prototype,"isDispersionEnabled",void 0),e([a(),s("_markScenePrePassDirty")],Us.prototype,"isScatteringEnabled",void 0),e([a()],Us.prototype,"_scatteringDiffusionProfileIndex",void 0),e([a()],Us.prototype,"refractionIntensity",void 0),e([a()],Us.prototype,"translucencyIntensity",void 0),e([a()],Us.prototype,"useAlbedoToTintRefraction",void 0),e([a()],Us.prototype,"useAlbedoToTintTranslucency",void 0),e([o(),s("_markAllSubMeshesAsTexturesDirty")],Us.prototype,"thicknessTexture",void 0),e([o(),s("_markAllSubMeshesAsTexturesDirty")],Us.prototype,"refractionTexture",void 0),e([a(),s("_markAllSubMeshesAsTexturesDirty")],Us.prototype,"indexOfRefraction",void 0),e([a()],Us.prototype,"_volumeIndexOfRefraction",void 0),e([s("_markAllSubMeshesAsTexturesDirty")],Us.prototype,"volumeIndexOfRefraction",null),e([a(),s("_markAllSubMeshesAsTexturesDirty")],Us.prototype,"invertRefractionY",void 0),e([a(),s("_markAllSubMeshesAsTexturesDirty")],Us.prototype,"linkRefractionWithTransparency",void 0),e([a()],Us.prototype,"minimumThickness",void 0),e([a()],Us.prototype,"maximumThickness",void 0),e([a()],Us.prototype,"useThicknessAsDepth",void 0),e([l()],Us.prototype,"tintColor",void 0),e([a()],Us.prototype,"tintColorAtDistance",void 0),e([a()],Us.prototype,"dispersion",void 0),e([l()],Us.prototype,"diffusionDistance",void 0),e([a(),s("_markAllSubMeshesAsTexturesDirty")],Us.prototype,"useMaskFromThicknessTexture",void 0),e([o(),s("_markAllSubMeshesAsTexturesDirty")],Us.prototype,"refractionIntensityTexture",void 0),e([o(),s("_markAllSubMeshesAsTexturesDirty")],Us.prototype,"translucencyIntensityTexture",void 0),e([l()],Us.prototype,"translucencyColor",void 0),e([o(),s("_markAllSubMeshesAsTexturesDirty")],Us.prototype,"translucencyColorTexture",void 0),e([a(),s("_markAllSubMeshesAsTexturesDirty")],Us.prototype,"useGltfStyleTextures",void 0);class Bs extends ls{constructor(){super(...arguments),this.DETAIL=!1,this.DETAILDIRECTUV=0,this.DETAIL_NORMALBLENDMETHOD=0}}class Gs extends fs{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}isCompatible(){return!0}constructor(e,t=!0){super(e,"DetailMap",140,new Bs,t),this._texture=null,this.diffuseBlendLevel=1,this.roughnessBlendLevel=1,this.bumpLevel=1,this._normalBlendMethod=Ji.MATERIAL_NORMALBLENDMETHOD_WHITEOUT,this._isEnabled=!1,this.isEnabled=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[Ze.MATERIAL_TextureDirtyFlag]}isReadyForSubMesh(e,t,i){return!this._isEnabled||!(e._areTexturesDirty&&t.texturesEnabled&&i.getCaps().standardDerivatives&&this._texture&&Es.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&&Es.DetailTextureEnabled&&this._isEnabled?(zi(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&&Es.DetailTextureEnabled&&(e.updateFloat4("vDetailInfos",this._texture.coordinatesIndex,this.diffuseBlendLevel,this.bumpLevel,this.roughnessBlendLevel),Yi(this._texture,e,"detail")),t.texturesEnabled&&this._texture&&Es.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"}]}}}e([o("detailTexture"),s("_markAllSubMeshesAsTexturesDirty")],Gs.prototype,"texture",void 0),e([a()],Gs.prototype,"diffuseBlendLevel",void 0),e([a()],Gs.prototype,"roughnessBlendLevel",void 0),e([a()],Gs.prototype,"bumpLevel",void 0),e([a(),s("_markAllSubMeshesAsTexturesDirty")],Gs.prototype,"normalBlendMethod",void 0),e([a(),s("_markAllSubMeshesAsTexturesDirty")],Gs.prototype,"isEnabled",void 0);const Vs={effect:null,subMesh:null};class ks extends ls{constructor(e){super(e),this.PBR=!0,this.NUM_SAMPLES="0",this.REALTIME_FILTERING=!1,this.MAINUV1=!1,this.MAINUV2=!1,this.MAINUV3=!1,this.MAINUV4=!1,this.MAINUV5=!1,this.MAINUV6=!1,this.UV1=!1,this.UV2=!1,this.UV3=!1,this.UV4=!1,this.UV5=!1,this.UV6=!1,this.ALBEDO=!1,this.GAMMAALBEDO=!1,this.ALBEDODIRECTUV=0,this.VERTEXCOLOR=!1,this.BAKED_VERTEX_ANIMATION_TEXTURE=!1,this.AMBIENT=!1,this.AMBIENTDIRECTUV=0,this.AMBIENTINGRAYSCALE=!1,this.OPACITY=!1,this.VERTEXALPHA=!1,this.OPACITYDIRECTUV=0,this.OPACITYRGB=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.ALPHABLEND=!1,this.ALPHAFROMALBEDO=!1,this.ALPHATESTVALUE="0.5",this.SPECULAROVERALPHA=!1,this.RADIANCEOVERALPHA=!1,this.ALPHAFRESNEL=!1,this.LINEARALPHAFRESNEL=!1,this.PREMULTIPLYALPHA=!1,this.EMISSIVE=!1,this.EMISSIVEDIRECTUV=0,this.GAMMAEMISSIVE=!1,this.REFLECTIVITY=!1,this.REFLECTIVITY_GAMMA=!1,this.REFLECTIVITYDIRECTUV=0,this.SPECULARTERM=!1,this.MICROSURFACEFROMREFLECTIVITYMAP=!1,this.MICROSURFACEAUTOMATIC=!1,this.LODBASEDMICROSFURACE=!1,this.MICROSURFACEMAP=!1,this.MICROSURFACEMAPDIRECTUV=0,this.METALLICWORKFLOW=!1,this.ROUGHNESSSTOREINMETALMAPALPHA=!1,this.ROUGHNESSSTOREINMETALMAPGREEN=!1,this.METALLNESSSTOREINMETALMAPBLUE=!1,this.AOSTOREINMETALMAPRED=!1,this.METALLIC_REFLECTANCE=!1,this.METALLIC_REFLECTANCE_GAMMA=!1,this.METALLIC_REFLECTANCEDIRECTUV=0,this.METALLIC_REFLECTANCE_USE_ALPHA_ONLY=!1,this.REFLECTANCE=!1,this.REFLECTANCE_GAMMA=!1,this.REFLECTANCEDIRECTUV=0,this.ENVIRONMENTBRDF=!1,this.ENVIRONMENTBRDF_RGBD=!1,this.NORMAL=!1,this.TANGENT=!1,this.BUMP=!1,this.BUMPDIRECTUV=0,this.OBJECTSPACE_NORMALMAP=!1,this.PARALLAX=!1,this.PARALLAX_RHS=!1,this.PARALLAXOCCLUSION=!1,this.NORMALXYSCALE=!0,this.LIGHTMAP=!1,this.LIGHTMAPDIRECTUV=0,this.USELIGHTMAPASSHADOWMAP=!1,this.GAMMALIGHTMAP=!1,this.RGBDLIGHTMAP=!1,this.REFLECTION=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,this.REFLECTIONMAP_PROJECTION=!1,this.REFLECTIONMAP_SKYBOX=!1,this.REFLECTIONMAP_EXPLICIT=!1,this.REFLECTIONMAP_EQUIRECTANGULAR=!1,this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,this.INVERTCUBICMAP=!1,this.USESPHERICALFROMREFLECTIONMAP=!1,this.USEIRRADIANCEMAP=!1,this.USESPHERICALINVERTEX=!1,this.REFLECTIONMAP_OPPOSITEZ=!1,this.LODINREFLECTIONALPHA=!1,this.GAMMAREFLECTION=!1,this.RGBDREFLECTION=!1,this.LINEARSPECULARREFLECTION=!1,this.RADIANCEOCCLUSION=!1,this.HORIZONOCCLUSION=!1,this.INSTANCES=!1,this.THIN_INSTANCES=!1,this.INSTANCESCOLOR=!1,this.PREPASS=!1,this.PREPASS_IRRADIANCE=!1,this.PREPASS_IRRADIANCE_INDEX=-1,this.PREPASS_ALBEDO_SQRT=!1,this.PREPASS_ALBEDO_SQRT_INDEX=-1,this.PREPASS_DEPTH=!1,this.PREPASS_DEPTH_INDEX=-1,this.PREPASS_NORMAL=!1,this.PREPASS_NORMAL_INDEX=-1,this.PREPASS_NORMAL_WORLDSPACE=!1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_VELOCITY=!1,this.PREPASS_VELOCITY_INDEX=-1,this.PREPASS_REFLECTIVITY=!1,this.PREPASS_REFLECTIVITY_INDEX=-1,this.SCENE_MRT_COUNT=0,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!1,this.BONES_VELOCITY_ENABLED=!1,this.NONUNIFORMSCALING=!1,this.MORPHTARGETS=!1,this.MORPHTARGETS_NORMAL=!1,this.MORPHTARGETS_TANGENT=!1,this.MORPHTARGETS_UV=!1,this.NUM_MORPH_INFLUENCERS=0,this.MORPHTARGETS_TEXTURE=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=0,this.CONTRAST=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.EXPOSURE=!1,this.MULTIVIEW=!1,this.ORDER_INDEPENDENT_TRANSPARENCY=!1,this.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!1,this.USEPHYSICALLIGHTFALLOFF=!1,this.USEGLTFLIGHTFALLOFF=!1,this.TWOSIDEDLIGHTING=!1,this.SHADOWFLOAT=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.POINTSIZE=!1,this.FOG=!1,this.LOGARITHMICDEPTH=!1,this.CAMERA_ORTHOGRAPHIC=!1,this.CAMERA_PERSPECTIVE=!1,this.FORCENORMALFORWARD=!1,this.SPECULARAA=!1,this.UNLIT=!1,this.DECAL_AFTER_DETAIL=!1,this.DEBUGMODE=0,this.rebuild()}reset(){super.reset(),this.ALPHATESTVALUE="0.5",this.PBR=!0,this.NORMALXYSCALE=!0}}class Xs extends gs{get realTimeFiltering(){return this._realTimeFiltering}set realTimeFiltering(e){this._realTimeFiltering=e,this.markAsDirty(Ze.MATERIAL_TextureDirtyFlag)}get realTimeFilteringQuality(){return this._realTimeFilteringQuality}set realTimeFilteringQuality(e){this._realTimeFilteringQuality=e,this.markAsDirty(Ze.MATERIAL_TextureDirtyFlag)}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),this._directIntensity=1,this._emissiveIntensity=1,this._environmentIntensity=1,this._specularIntensity=1,this._lightingInfos=new G(this._directIntensity,this._emissiveIntensity,this._environmentIntensity,this._specularIntensity),this._disableBumpMap=!1,this._albedoTexture=null,this._ambientTexture=null,this._ambientTextureStrength=1,this._ambientTextureImpactOnAnalyticalLights=Xs.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=ee.White(),this._useOnlyMetallicFromMetallicReflectanceTexture=!1,this._metallicReflectanceTexture=null,this._reflectanceTexture=null,this._microSurfaceTexture=null,this._bumpTexture=null,this._lightmapTexture=null,this._ambientColor=new ee(0,0,0),this._albedoColor=new ee(1,1,1),this._reflectivityColor=new ee(1,1,1),this._reflectionColor=new ee(1,1,1),this._emissiveColor=new ee(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=Xs.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=Ze.TEXTURE_FILTERING_QUALITY_LOW,this._forceNormalForward=!1,this._enableSpecularAntiAliasing=!1,this._imageProcessingObserver=null,this._renderTargets=new Zt(16),this._globalAmbientColor=new ee(0,0,0),this._unlit=!1,this._applyDecalMapAfterDetailMap=!1,this._debugMode=0,this._shadersLoaded=!1,this._breakShaderLoadedCheck=!1,this.debugMode=0,this.debugLimit=-1,this.debugFactor=1,this._cacheHasRenderTargetTextures=!1;const n=this.getScene().getEngine();!n.isWebGPU||i||Xs.ForceGLSL||(this._uniformBuffer&&this._uniformBuffer.dispose(),this._uniformBuffer=new Pi(n,void 0,void 0,this.name,!0),this._shaderLanguage=1),this.brdf=new ms(this),this.clearCoat=new ys(this),this.iridescence=new Ds(this),this.anisotropy=new Ps(this),this.sheen=new Fs(this),this.subSurface=new Us(this),this.detailMap=new Gs(this),this._attachImageProcessingConfiguration(null),this.getRenderTargetTextures=()=>(this._renderTargets.reset(),Es.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),this._eventInfo.renderTargets=this._renderTargets,this._callbackPluginEventFillRenderTargetTextures(this._eventInfo),this._renderTargets),this._environmentBRDFTexture=os(this.getScene()),this.prePassConfiguration=new ps}get hasRenderTargetTextures(){return!!(Es.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget)||this._cacheHasRenderTargetTextures}get isPrePassCapable(){return!this.disableDepthWrite}getClassName(){return"PBRBaseMaterial"}get _disableAlphaBlending(){return this._transparencyMode===Xs.PBRMATERIAL_OPAQUE||this._transparencyMode===Xs.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===Xs.PBRMATERIAL_ALPHATEST))}_shouldUseAlphaFromAlbedoTexture(){return null!=this._albedoTexture&&this._albedoTexture.hasAlpha&&this._useAlphaFromAlbedoTexture&&this._transparencyMode!==Xs.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 n=t._drawWrapper;if(n.effect&&this.isFrozen&&n._wasPreviouslyReady&&n._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(this._callbackPluginEventGeneric(4,this._eventInfo),t.materialDefines=new ks(this._eventInfo.defineNames));const r=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const s=this.getScene(),a=s.getEngine();if(r._areTexturesDirty&&(this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,s.texturesEnabled)){if(this._albedoTexture&&Es.DiffuseTextureEnabled&&!this._albedoTexture.isReadyOrNotBlocking())return!1;if(this._ambientTexture&&Es.AmbientTextureEnabled&&!this._ambientTexture.isReadyOrNotBlocking())return!1;if(this._opacityTexture&&Es.OpacityTextureEnabled&&!this._opacityTexture.isReadyOrNotBlocking())return!1;const e=this._getReflectionTexture();if(e&&Es.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&&Es.LightmapTextureEnabled&&!this._lightmapTexture.isReadyOrNotBlocking())return!1;if(this._emissiveTexture&&Es.EmissiveTextureEnabled&&!this._emissiveTexture.isReadyOrNotBlocking())return!1;if(Es.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(a.getCaps().standardDerivatives&&this._bumpTexture&&Es.BumpTextureEnabled&&!this._disableBumpMap&&!this._bumpTexture.isReady())return!1;if(this._environmentBRDFTexture&&Es.ReflectionTextureEnabled&&!this._environmentBRDFTexture.isReady())return!1}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=r,this._eventInfo.subMesh=t,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh)return!1;if(r._areImageProcessingDirty&&this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady())return!1;a.getCaps().standardDerivatives||e.isVerticesDataPresent(si.NormalKind)||(e.createNormals(!0),de.Warn("PBRMaterial: Normals have been created for the mesh: "+e.name));const o=t.effect,l=r._areLightsDisposed;let c=this._prepareEffect(e,r,this.onCompiled,this.onError,i,null,t.getRenderingMesh().hasThinInstances),h=!1;if(c)if(this._onEffectCreatedObservable&&(Vs.effect=c,Vs.subMesh=t,this._onEffectCreatedObservable.notifyObservers(Vs)),this.allowShaderHotSwapping&&o&&!c.isReady()){if(c=o,r.markAsUnprocessed(),h=this.isFrozen,l)return r._areLightsDisposed=!0,!1}else s.resetCachedMaterial(),t.setEffect(c,r,this._materialContext);return!(!t.effect||!t.effect.isReady())&&(r._renderId=s.getRenderId(),n._wasPreviouslyReady=!h,n._wasPreviouslyUsingInstances=!!i,this._checkScenePerformancePriority(),!0)}isMetallicWorkflow(){return!(null==this._metallic&&null==this._roughness&&!this._metallicTexture)}_prepareEffect(e,t,i=null,n=null,r=null,s=null,a){if(this._prepareDefines(e,t,r,s,a),!t.isDirty)return null;t.markAsProcessed();const o=this.getScene().getEngine(),l=new xs;let c=0;t.USESPHERICALINVERTEX&&l.addFallback(c++,"USESPHERICALINVERTEX"),t.FOG&&l.addFallback(c,"FOG"),t.SPECULARAA&&l.addFallback(c,"SPECULARAA"),t.POINTSIZE&&l.addFallback(c,"POINTSIZE"),t.LOGARITHMICDEPTH&&l.addFallback(c,"LOGARITHMICDEPTH"),t.PARALLAX&&l.addFallback(c,"PARALLAX"),t.PARALLAX_RHS&&l.addFallback(c,"PARALLAX_RHS"),t.PARALLAXOCCLUSION&&l.addFallback(c++,"PARALLAXOCCLUSION"),t.ENVIRONMENTBRDF&&l.addFallback(c++,"ENVIRONMENTBRDF"),t.TANGENT&&l.addFallback(c++,"TANGENT"),t.BUMP&&l.addFallback(c++,"BUMP"),c=function(e,t,i=4,n=0){let r=0;for(let s=0;s<i&&e["LIGHT"+s];s++)s>0&&(r=n+s,t.addFallback(r,"LIGHT"+s)),e.SHADOWS||(e["SHADOW"+s]&&t.addFallback(n,"SHADOW"+s),e["SHADOWPCF"+s]&&t.addFallback(n,"SHADOWPCF"+s),e["SHADOWPCSS"+s]&&t.addFallback(n,"SHADOWPCSS"+s),e["SHADOWPOISSON"+s]&&t.addFallback(n,"SHADOWPOISSON"+s),e["SHADOWESM"+s]&&t.addFallback(n,"SHADOWESM"+s),e["SHADOWCLOSEESM"+s]&&t.addFallback(n,"SHADOWCLOSEESM"+s));return r++}(t,l,this._maxSimultaneousLights,c++),t.SPECULARTERM&&l.addFallback(c++,"SPECULARTERM"),t.USESPHERICALFROMREFLECTIONMAP&&l.addFallback(c++,"USESPHERICALFROMREFLECTIONMAP"),t.USEIRRADIANCEMAP&&l.addFallback(c++,"USEIRRADIANCEMAP"),t.LIGHTMAP&&l.addFallback(c++,"LIGHTMAP"),t.NORMAL&&l.addFallback(c++,"NORMAL"),t.AMBIENT&&l.addFallback(c++,"AMBIENT"),t.EMISSIVE&&l.addFallback(c++,"EMISSIVE"),t.VERTEXCOLOR&&l.addFallback(c++,"VERTEXCOLOR"),t.MORPHTARGETS&&l.addFallback(c++,"MORPHTARGETS"),t.MULTIVIEW&&l.addFallback(0,"MULTIVIEW");const h=[si.PositionKind];t.NORMAL&&h.push(si.NormalKind),t.TANGENT&&h.push(si.TangentKind);for(let e=1;e<=Ze.MAX_SUPPORTED_UV_SETS;++e)t["UV"+e]&&h.push(`uv${1===e?"":e}`);t.VERTEXCOLOR&&h.push(si.ColorKind),function(e,t,i,n){i.NUM_BONE_INFLUENCERS>0&&(n.addCPUSkinningFallback(0,t),e.push(Ze.MatricesIndicesKind),e.push(Ze.MatricesWeightsKind),i.NUM_BONE_INFLUENCERS>4&&(e.push(Ze.MatricesIndicesExtraKind),e.push(Ze.MatricesWeightsExtraKind)))}(h,e,t,l),function(e,t){(t.INSTANCES||t.THIN_INSTANCES)&&function(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"))}(e,!!t.PREPASS_VELOCITY),t.INSTANCESCOLOR&&e.push(Ze.ColorInstanceKind)}(h,t),function(e,t,i){const n=i.NUM_MORPH_INFLUENCERS;if(n>0&&y.LastCreatedEngine){const r=y.LastCreatedEngine.getCaps().maxVertexAttribs,s=t.morphTargetManager;if(s?.isUsingTextureForTargets)return;const a=s&&s.supportsNormals&&i.NORMAL,o=s&&s.supportsTangents&&i.TANGENT,l=s&&s.supportsUVs&&i.UV1;for(let i=0;i<n;i++)e.push(Ze.PositionKind+i),a&&e.push(Ze.NormalKind+i),o&&e.push(Ze.TangentKind+i),l&&e.push(Ze.UVKind+"_"+i),e.length>r&&de.Error("Cannot add more vertex attributes for mesh "+t.name)}}(h,e,t),function(e,t,i){i.BAKED_VERTEX_ANIMATION_TEXTURE&&i.INSTANCES&&e.push("bakedVertexAnimationSettingsInstanced")}(h,0,t);let d="pbr";const u=["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"],f=["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=l,this._eventInfo.fallbackRank=c,this._eventInfo.defines=t,this._eventInfo.uniforms=u,this._eventInfo.attributes=h,this._eventInfo.samplers=f,this._eventInfo.uniformBuffersNames=_,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._eventInfo.indexParameters=m,this._callbackPluginEventGeneric(128,this._eventInfo),ps.AddUniforms(u),function(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")}(u),qn&&(qn.PrepareUniforms(u,t),qn.PrepareSamplers(f,t)),function(e,t,i,n=4){let r,s=null;if(e.uniformsNames){const a=e;r=a.uniformsNames,s=a.uniformBuffersNames,t=a.samplers,i=a.defines,n=a.maxSimultaneousLights||0}else r=e,t||(t=[]);for(let e=0;e<n&&i["LIGHT"+e];e++)Zi(e,r,t,i["PROJECTEDLIGHTTEXTURE"+e],s);i.NUM_MORPH_INFLUENCERS&&(r.push("morphTargetInfluences"),r.push("morphTargetCount")),i.BAKED_VERTEX_ANIMATION_TEXTURE&&(r.push("bakedVertexAnimationSettings"),r.push("bakedVertexAnimationTextureSizeInverted"),r.push("bakedVertexAnimationTime"),t.push("bakedVertexAnimationTexture"))}({uniformsNames:u,uniformBuffersNames:_,samplers:f,defines:t,maxSimultaneousLights:this._maxSimultaneousLights});const p={};this.customShaderNameResolve&&(d=this.customShaderNameResolve(d,u,_,f,t,h,p));const g=t.toString(),E=o.createEffect(d,{attributes:h,uniformsNames:u,uniformBuffersNames:_,samplers:f,defines:g,fallbacks:l,onCompiled:i,onError:n,indexParameters:m,processFinalCode:p.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((function(){return Lu})),Promise.resolve().then((function(){return Bu}))]):await Promise.all([Promise.resolve().then((function(){return Xu})),Promise.resolve().then((function(){return Yu}))]),this._shadersLoaded=!0}},o);return this._eventInfo.customCode=void 0,E}_prepareDefines(e,t,i=null,n=null,r=!1){const s=this.getScene(),a=s.getEngine();!function(e,t,i,n,r=4,s=!1){if(!i._areLightsDirty)return i._needNormals;let a=0;const o={needNormals:i._needNormals,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};if(e.lightsEnabled&&!s)for(const n of t.lightSources)if(ji(e,t,n,a,i,0,o),a++,a===r)break;i.SPECULARTERM=o.specularEnabled,i.SHADOWS=o.shadowEnabled;for(let e=a;e<r;e++)void 0!==i["LIGHT"+e]&&(i["LIGHT"+e]=!1,i["HEMILIGHT"+e]=!1,i["POINTLIGHT"+e]=!1,i["DIRLIGHT"+e]=!1,i["SPOTLIGHT"+e]=!1,i["SHADOW"+e]=!1,i["SHADOWCSM"+e]=!1,i["SHADOWCSMDEBUG"+e]=!1,i["SHADOWCSMNUM_CASCADES"+e]=!1,i["SHADOWCSMUSESHADOWMAXZ"+e]=!1,i["SHADOWCSMNOBLEND"+e]=!1,i["SHADOWCSM_RIGHTHANDED"+e]=!1,i["SHADOWPCF"+e]=!1,i["SHADOWPCSS"+e]=!1,i["SHADOWPOISSON"+e]=!1,i["SHADOWESM"+e]=!1,i["SHADOWCLOSEESM"+e]=!1,i["SHADOWCUBE"+e]=!1,i["SHADOWLOWQUALITY"+e]=!1,i["SHADOWMEDIUMQUALITY"+e]=!1);const l=e.getEngine().getCaps();void 0===i.SHADOWFLOAT&&(o.needRebuild=!0),i.SHADOWFLOAT=o.shadowEnabled&&(l.textureFloatRender&&l.textureFloatLinearFiltering||l.textureHalfFloatRender&&l.textureHalfFloatLinearFiltering),i.LIGHTMAPEXCLUDED=o.lightmapMode,o.needRebuild&&i.rebuild(),o.needNormals}(s,e,t,0,this._maxSimultaneousLights,this._disableLighting),t._needNormals=!0,function(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()}}(s,t);const o=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(function(e,t,i){const n=t.PREPASS;if(!t._arePrePassDirty)return;const r=[{type:Ze.PREPASS_POSITION_TEXTURE_TYPE,define:"PREPASS_POSITION",index:"PREPASS_POSITION_INDEX"},{type:Ze.PREPASS_VELOCITY_TEXTURE_TYPE,define:"PREPASS_VELOCITY",index:"PREPASS_VELOCITY_INDEX"},{type:Ze.PREPASS_REFLECTIVITY_TEXTURE_TYPE,define:"PREPASS_REFLECTIVITY",index:"PREPASS_REFLECTIVITY_INDEX"},{type:Ze.PREPASS_IRRADIANCE_TEXTURE_TYPE,define:"PREPASS_IRRADIANCE",index:"PREPASS_IRRADIANCE_INDEX"},{type:Ze.PREPASS_ALBEDO_SQRT_TEXTURE_TYPE,define:"PREPASS_ALBEDO_SQRT",index:"PREPASS_ALBEDO_SQRT_INDEX"},{type:Ze.PREPASS_DEPTH_TEXTURE_TYPE,define:"PREPASS_DEPTH",index:"PREPASS_DEPTH_INDEX"},{type:Ze.PREPASS_NORMAL_TEXTURE_TYPE,define:"PREPASS_NORMAL",index:"PREPASS_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;for(let i=0;i<r.length;i++){const n=e.prePassRenderer.getIndex(r[i].type);-1!==n?(t[r[i].define]=!0,t[r[i].index]=n):t[r[i].define]=!1}}else{t.PREPASS=!1;for(let e=0;e<r.length;e++)t[r[e].define]=!1}t.PREPASS!=n&&(t.markAsUnprocessed(),t.markAsImageProcessingDirty())}(s,t,this.canRenderToMRT&&!o),function(e,t,i){const n=t.ORDER_INDEPENDENT_TRANSPARENCY,r=t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS;t.ORDER_INDEPENDENT_TRANSPARENCY=e.useOrderIndependentTransparency&&i,t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!e.getEngine().getCaps().textureFloatLinearFiltering,n===t.ORDER_INDEPENDENT_TRANSPARENCY&&r===t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS||t.markAsUnprocessed()}(s,t,o),t.METALLICWORKFLOW=this.isMetallicWorkflow(),t._areTexturesDirty){t._needUVs=!1;for(let e=1;e<=Ze.MAX_SUPPORTED_UV_SETS;++e)t["MAINUV"+e]=!1;if(s.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,a.getCaps().textureLOD&&(t.LODBASEDMICROSFURACE=!0),this._albedoTexture&&Es.DiffuseTextureEnabled?(zi(this._albedoTexture,t,"ALBEDO"),t.GAMMAALBEDO=this._albedoTexture.gammaSpace):t.ALBEDO=!1,this._ambientTexture&&Es.AmbientTextureEnabled?(zi(this._ambientTexture,t,"AMBIENT"),t.AMBIENTINGRAYSCALE=this._useAmbientInGrayScale):t.AMBIENT=!1,this._opacityTexture&&Es.OpacityTextureEnabled?(zi(this._opacityTexture,t,"OPACITY"),t.OPACITYRGB=this._opacityTexture.getAlphaFromRGB):t.OPACITY=!1;const e=this._getReflectionTexture();if(e&&Es.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,a._features.needTypeSuffixInShaderConstants&&(t.NUM_SAMPLES=t.NUM_SAMPLES+"u"),t.REALTIME_FILTERING=!0):t.REALTIME_FILTERING=!1,t.INVERTCUBICMAP=e.coordinatesMode===Pr.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 Pr.EXPLICIT_MODE:t.REFLECTIONMAP_EXPLICIT=!0;break;case Pr.PLANAR_MODE:t.REFLECTIONMAP_PLANAR=!0;break;case Pr.PROJECTION_MODE:t.REFLECTIONMAP_PROJECTION=!0;break;case Pr.SKYBOX_MODE:t.REFLECTIONMAP_SKYBOX=!0;break;case Pr.SPHERICAL_MODE:t.REFLECTIONMAP_SPHERICAL=!0;break;case Pr.EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case Pr.FIXED_EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case Pr.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case Pr.CUBIC_MODE:case Pr.INVCUBIC_MODE:default:t.REFLECTIONMAP_CUBIC=!0,t.USE_LOCAL_REFLECTIONMAP_CUBIC=!!e.boundingBoxSize}e.coordinatesMode!==Pr.SKYBOX_MODE&&(e.irradianceTexture?(t.USEIRRADIANCEMAP=!0,t.USESPHERICALFROMREFLECTIONMAP=!1):e.isCube&&(t.USESPHERICALFROMREFLECTIONMAP=!0,t.USEIRRADIANCEMAP=!1,this._forceIrradianceInFragment||this.realTimeFiltering||this._twoSidedLighting||a.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&&Es.LightmapTextureEnabled?(zi(this._lightmapTexture,t,"LIGHTMAP"),t.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,t.GAMMALIGHTMAP=this._lightmapTexture.gammaSpace,t.RGBDLIGHTMAP=this._lightmapTexture.isRGBD):t.LIGHTMAP=!1,this._emissiveTexture&&Es.EmissiveTextureEnabled?(zi(this._emissiveTexture,t,"EMISSIVE"),t.GAMMAEMISSIVE=this._emissiveTexture.gammaSpace):t.EMISSIVE=!1,Es.SpecularTextureEnabled?(this._metallicTexture?(zi(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?(zi(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?(zi(this._metallicReflectanceTexture,t,"METALLIC_REFLECTANCE"),t.METALLIC_REFLECTANCE_GAMMA=this._metallicReflectanceTexture.gammaSpace):t.METALLIC_REFLECTANCE=!1,this._reflectanceTexture&&(!this._metallicReflectanceTexture||this._metallicReflectanceTexture&&this._useOnlyMetallicFromMetallicReflectanceTexture)?(zi(this._reflectanceTexture,t,"REFLECTANCE"),t.REFLECTANCE_GAMMA=this._reflectanceTexture.gammaSpace):t.REFLECTANCE=!1):(t.METALLIC_REFLECTANCE=!1,t.REFLECTANCE=!1),this._microSurfaceTexture?zi(this._microSurfaceTexture,t,"MICROSURFACEMAP"):t.MICROSURFACEMAP=!1):(t.REFLECTIVITY=!1,t.MICROSURFACEMAP=!1),a.getCaps().standardDerivatives&&this._bumpTexture&&Es.BumpTextureEnabled&&!this._disableBumpMap?(zi(this._bumpTexture,t,"BUMP"),this._useParallax&&this._albedoTexture&&Es.DiffuseTextureEnabled?(t.PARALLAX=!0,t.PARALLAX_RHS=s.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&&Es.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===Xs.LIGHTFALLOFF_STANDARD?(t.USEPHYSICALLIGHTFALLOFF=!1,t.USEGLTFLIGHTFALLOFF=!1):this._lightFalloff===Xs.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=a.getCaps().standardDerivatives&&this._enableSpecularAntiAliasing}(t._areTexturesDirty||t._areMiscDirty)&&(t.ALPHATESTVALUE=`${this._alphaCutOff}${this._alphaCutOff%1==0?".":""}`,t.PREMULTIPLYALPHA=this.alphaMode===Ze.ALPHA_PREMULTIPLIED||this.alphaMode===Ze.ALPHA_PREMULTIPLIED_PORTERDUFF,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&&(qi(e,s,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e)||this._forceAlphaTest,t,this._applyDecalMapAfterDetailMap),t.UNLIT=this._unlit||(this.pointsCloud||this.wireframe)&&!e.isVerticesDataPresent(si.NormalKind),t.DEBUGMODE=this._debugMode),Qi(s,a,this,t,!!i,n,r),this._eventInfo.defines=t,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),function(e,t,i,n,r=!1,s=!0,a=!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(Ze.NormalKind),t._needNormals&&e.isVerticesDataPresent(Ze.TangentKind)&&(t.TANGENT=!0);for(let i=1;i<=Ze.MAX_SUPPORTED_UV_SETS;++i)t["UV"+i]=!!t._needUVs&&e.isVerticesDataPresent(`uv${1===i?"":i}`);{const i=e.useVertexColors&&e.isVerticesDataPresent(Ze.ColorKind);t.VERTEXCOLOR=i,t.VERTEXALPHA=e.hasVertexAlpha&&i&&s}e.isVerticesDataPresent(Ze.ColorInstanceKind)&&(e.hasInstances||e.hasThinInstances)&&(t.INSTANCESCOLOR=!0),function(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 n=e.getScene().prePassRenderer;if(n&&n.enabled){const i=-1===n.excludedSkinnedMesh.indexOf(e);t.BONES_VELOCITY_ENABLED=i}}}else t.NUM_BONE_INFLUENCERS=0,t.BonesPerMesh=0,void 0!==t.BONETEXTURE&&(t.BONETEXTURE=!1)}(e,t),r&&function(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)}(e,t),a&&function(e,t){const i=e.bakedVertexAnimationManager;t.BAKED_VERTEX_ANIMATION_TEXTURE=!(!i||!i.isEnabled)}(e,t)}(e,t,0,0,!0,this._transparencyMode!==Xs.PBRMATERIAL_OPAQUE),this._callbackPluginEventPrepareDefines(this._eventInfo)}forceCompilation(e,t,i){const n={clipPlane:!1,useInstances:!1,...i};this._uniformBufferLayoutBuilt||this.buildUniformLayout(),this._callbackPluginEventGeneric(4,this._eventInfo);(()=>{if(this._breakShaderLoadedCheck)return;const i=new ks(this._eventInfo.defineNames),r=this._prepareEffect(e,i,void 0,void 0,n.useInstances,n.clipPlane,e.hasThinInstances);this._onEffectCreatedObservable&&(Vs.effect=r,Vs.subMesh=null,this._onEffectCreatedObservable.notifyObservers(Vs)),r.isReady()?t&&t(this):r.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 n=this.getScene(),r=i.materialDefines;if(!r)return;const s=i.effect;if(!s)return;this._activeEffect=s,t.getMeshUniformBuffer().bindToEffect(s,"Mesh"),t.transferToEffect(e);const a=n.getEngine();this._uniformBuffer.bindToEffect(s,"Material"),this.prePassConfiguration.bindForSubMesh(this._activeEffect,n,t,e,this.isFrozen),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),r.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));const o=this._mustRebind(n,s,i,t.visibility);!function(e,t,i){var n;if(t&&e&&(e.computeBonesUsingShaders&&t._bonesComputationForcedToCPU&&(e.computeBonesUsingShaders=!1),e.useBones&&e.computeBonesUsingShaders&&e.skeleton)){const r=e.skeleton;if(r.isUsingTextureForMatrices&&t.getUniformIndex("boneTextureWidth")>-1){const i=r.getTransformMatrixTexture(e);t.setTexture("boneSampler",i),t.setFloat("boneTextureWidth",4*(r.bones.length+1))}else{const s=r.getTransformMatrices(e);s&&(t.setMatrices("mBones",s),i&&e.getScene().prePassRenderer&&e.getScene().prePassRenderer.getIndex(Ze.PREPASS_VELOCITY_TEXTURE_TYPE)&&(i.previousBones[e.uniqueId]||(i.previousBones[e.uniqueId]=s.slice()),t.setMatrices("mPreviousBones",i.previousBones[e.uniqueId]),n=s,i.previousBones[e.uniqueId].set(n)))}}}(t,this._activeEffect,this.prePassConfiguration);let l=null;const c=this._uniformBuffer;if(o){if(this.bindViewProjection(s),l=this._getReflectionTexture(),!c.useUbo||!this.isFrozen||!c.isSync||i._drawWrapper._forceRebindOnNextCall){if(n.texturesEnabled){if(this._albedoTexture&&Es.DiffuseTextureEnabled&&(c.updateFloat2("vAlbedoInfos",this._albedoTexture.coordinatesIndex,this._albedoTexture.level),Yi(this._albedoTexture,c,"albedo")),this._ambientTexture&&Es.AmbientTextureEnabled&&(c.updateFloat4("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level,this._ambientTextureStrength,this._ambientTextureImpactOnAnalyticalLights),Yi(this._ambientTexture,c,"ambient")),this._opacityTexture&&Es.OpacityTextureEnabled&&(c.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),Yi(this._opacityTexture,c,"opacity")),l&&Es.ReflectionTextureEnabled){if(c.updateMatrix("reflectionMatrix",l.getReflectionTextureMatrix()),c.updateFloat2("vReflectionInfos",l.level,0),l.boundingBoxSize){const e=l;c.updateVector3("vReflectionPosition",e.boundingBoxPosition),c.updateVector3("vReflectionSize",e.boundingBoxSize)}if(this.realTimeFiltering){const e=l.getSize().width;c.updateFloat2("vReflectionFilteringInfo",e,j.Log2(e))}if(!r.USEIRRADIANCEMAP){const e=l.sphericalPolynomial;if(r.USESPHERICALFROMREFLECTIONMAP&&e)if(r.SPHERICAL_HARMONICS){const t=e.preScaledHarmonics;c.updateVector3("vSphericalL00",t.l00),c.updateVector3("vSphericalL1_1",t.l1_1),c.updateVector3("vSphericalL10",t.l10),c.updateVector3("vSphericalL11",t.l11),c.updateVector3("vSphericalL2_2",t.l2_2),c.updateVector3("vSphericalL2_1",t.l2_1),c.updateVector3("vSphericalL20",t.l20),c.updateVector3("vSphericalL21",t.l21),c.updateVector3("vSphericalL22",t.l22)}else c.updateFloat3("vSphericalX",e.x.x,e.x.y,e.x.z),c.updateFloat3("vSphericalY",e.y.x,e.y.y,e.y.z),c.updateFloat3("vSphericalZ",e.z.x,e.z.y,e.z.z),c.updateFloat3("vSphericalXX_ZZ",e.xx.x-e.zz.x,e.xx.y-e.zz.y,e.xx.z-e.zz.z),c.updateFloat3("vSphericalYY_ZZ",e.yy.x-e.zz.x,e.yy.y-e.zz.y,e.yy.z-e.zz.z),c.updateFloat3("vSphericalZZ",e.zz.x,e.zz.y,e.zz.z),c.updateFloat3("vSphericalXY",e.xy.x,e.xy.y,e.xy.z),c.updateFloat3("vSphericalYZ",e.yz.x,e.yz.y,e.yz.z),c.updateFloat3("vSphericalZX",e.zx.x,e.zx.y,e.zx.z)}c.updateFloat3("vReflectionMicrosurfaceInfos",l.getSize().width,l.lodGenerationScale,l.lodGenerationOffset)}this._emissiveTexture&&Es.EmissiveTextureEnabled&&(c.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),Yi(this._emissiveTexture,c,"emissive")),this._lightmapTexture&&Es.LightmapTextureEnabled&&(c.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),Yi(this._lightmapTexture,c,"lightmap")),Es.SpecularTextureEnabled&&(this._metallicTexture?(c.updateFloat3("vReflectivityInfos",this._metallicTexture.coordinatesIndex,this._metallicTexture.level,this._ambientTextureStrength),Yi(this._metallicTexture,c,"reflectivity")):this._reflectivityTexture&&(c.updateFloat3("vReflectivityInfos",this._reflectivityTexture.coordinatesIndex,this._reflectivityTexture.level,1),Yi(this._reflectivityTexture,c,"reflectivity")),this._metallicReflectanceTexture&&(c.updateFloat2("vMetallicReflectanceInfos",this._metallicReflectanceTexture.coordinatesIndex,this._metallicReflectanceTexture.level),Yi(this._metallicReflectanceTexture,c,"metallicReflectance")),this._reflectanceTexture&&r.REFLECTANCE&&(c.updateFloat2("vReflectanceInfos",this._reflectanceTexture.coordinatesIndex,this._reflectanceTexture.level),Yi(this._reflectanceTexture,c,"reflectance")),this._microSurfaceTexture&&(c.updateFloat2("vMicroSurfaceSamplerInfos",this._microSurfaceTexture.coordinatesIndex,this._microSurfaceTexture.level),Yi(this._microSurfaceTexture,c,"microSurfaceSampler"))),this._bumpTexture&&a.getCaps().standardDerivatives&&Es.BumpTextureEnabled&&!this._disableBumpMap&&(c.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level,this._parallaxScaleBias),Yi(this._bumpTexture,c,"bump"),n._mirroredCameraPosition?c.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):c.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1))}if(this.pointsCloud&&c.updateFloat("pointSize",this.pointSize),r.METALLICWORKFLOW){ie.Color3[0].r=void 0===this._metallic||null===this._metallic?1:this._metallic,ie.Color3[0].g=void 0===this._roughness||null===this._roughness?1:this._roughness,c.updateColor4("vReflectivityColor",ie.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,ie.Color3[0]);const n=this._metallicF0Factor;c.updateColor4("vMetallicReflectanceFactors",ie.Color3[0],n)}else c.updateColor4("vReflectivityColor",this._reflectivityColor,this._microSurface);c.updateColor3("vEmissiveColor",Es.EmissiveTextureEnabled?this._emissiveColor:ee.BlackReadOnly),c.updateColor3("vReflectionColor",this._reflectionColor),!r.SS_REFRACTION&&this.subSurface?._linkRefractionWithTransparency?c.updateColor4("vAlbedoColor",this._albedoColor,1):c.updateColor4("vAlbedoColor",this._albedoColor,this.alpha),this._lightingInfos.x=this._directIntensity,this._lightingInfos.y=this._emissiveIntensity,this._lightingInfos.z=this._environmentIntensity*n.environmentIntensity,this._lightingInfos.w=this._specularIntensity,c.updateVector4("vLightingIntensity",this._lightingInfos),n.ambientColor.multiplyToRef(this._ambientColor,this._globalAmbientColor),c.updateColor3("vAmbientColor",this._globalAmbientColor),c.updateFloat2("vDebugMode",this.debugLimit,this.debugFactor)}n.texturesEnabled&&(this._albedoTexture&&Es.DiffuseTextureEnabled&&c.setTexture("albedoSampler",this._albedoTexture),this._ambientTexture&&Es.AmbientTextureEnabled&&c.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&Es.OpacityTextureEnabled&&c.setTexture("opacitySampler",this._opacityTexture),l&&Es.ReflectionTextureEnabled&&(r.LODBASEDMICROSFURACE?c.setTexture("reflectionSampler",l):(c.setTexture("reflectionSampler",l._lodTextureMid||l),c.setTexture("reflectionSamplerLow",l._lodTextureLow||l),c.setTexture("reflectionSamplerHigh",l._lodTextureHigh||l)),r.USEIRRADIANCEMAP&&c.setTexture("irradianceSampler",l.irradianceTexture)),r.ENVIRONMENTBRDF&&c.setTexture("environmentBrdfSampler",this._environmentBRDFTexture),this._emissiveTexture&&Es.EmissiveTextureEnabled&&c.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&Es.LightmapTextureEnabled&&c.setTexture("lightmapSampler",this._lightmapTexture),Es.SpecularTextureEnabled&&(this._metallicTexture?c.setTexture("reflectivitySampler",this._metallicTexture):this._reflectivityTexture&&c.setTexture("reflectivitySampler",this._reflectivityTexture),this._metallicReflectanceTexture&&c.setTexture("metallicReflectanceSampler",this._metallicReflectanceTexture),this._reflectanceTexture&&r.REFLECTANCE&&c.setTexture("reflectanceSampler",this._reflectanceTexture),this._microSurfaceTexture&&c.setTexture("microSurfaceSampler",this._microSurfaceTexture)),this._bumpTexture&&a.getCaps().standardDerivatives&&Es.BumpTextureEnabled&&!this._disableBumpMap&&c.setTexture("bumpSampler",this._bumpTexture)),this.getScene().useOrderIndependentTransparency&&this.needAlphaBlendingForMesh(t)&&this.getScene().depthPeelingRenderer.bind(s),this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),function(e,t,i){let n=t.clipPlane??i.clipPlane;Hi(e,"vClipPlane",n),n=t.clipPlane2??i.clipPlane2,Hi(e,"vClipPlane2",n),n=t.clipPlane3??i.clipPlane3,Hi(e,"vClipPlane3",n),n=t.clipPlane4??i.clipPlane4,Hi(e,"vClipPlane4",n),n=t.clipPlane5??i.clipPlane5,Hi(e,"vClipPlane5",n),n=t.clipPlane6??i.clipPlane6,Hi(e,"vClipPlane6",n)}(this._activeEffect,this,n),this.bindEyePosition(s)}else n.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);!o&&this.isFrozen||(n.lightsEnabled&&!this._disableLighting&&function(e,t,i,n,r=4){const s=Math.min(t.lightSources.length,r);for(let r=0;r<s;r++)Ki(t.lightSources[r],r,e,i,"boolean"==typeof n?n:n.SPECULARTERM,t.receiveShadows)}(n,t,this._activeEffect,r,this._maxSimultaneousLights),(n.fogEnabled&&t.applyFog&&n.fogMode!==Rr.FOGMODE_NONE||l||this.subSurface.refractionTexture||t.receiveShadows||r.PREPASS)&&this.bindView(s),function(e,t,i,n=!1){i&&e.fogEnabled&&(!t||t.applyFog)&&e.fogMode!==Ze.FOGMODE_NONE&&(i.setFloat4("vFogInfos",e.fogMode,e.fogStart,e.fogEnd,e.fogDensity),n?(e.fogColor.toLinearSpaceToRef(Wi,e.getEngine().useExactSrgbConversions),i.setColor3("vFogColor",Wi)):i.setColor3("vFogColor",e.fogColor))}(n,t,this._activeEffect,!0),r.NUM_MORPH_INFLUENCERS&&function(e,t){const i=e.morphTargetManager;e&&i&&t.setFloatArray("morphTargetInfluences",i.influences)}(t,this._activeEffect),r.BAKED_VERTEX_ANIMATION_TEXTURE&&t.bakedVertexAnimationManager?.bind(s,r.INSTANCES),this._imageProcessingConfiguration.bind(this._activeEffect),function(e,t,i){if(!e||e.LOGARITHMICDEPTH||e.indexOf&&e.indexOf("LOGARITHMICDEPTH")>=0){const e=i.activeCamera;e.mode===Ze.ORTHOGRAPHIC_CAMERA&&de.Error("Logarithmic depth is not compatible with orthographic cameras!",20),t.setFloat("logarithmicDepthConstant",2/(Math.log(e.maxZ+1)/Math.LN2))}}(r,this._activeEffect,n)),this._afterBind(t,this._activeEffect,i),c.update()}getAnimatables(){const e=super.getAnimatables();return this._albedoTexture&&this._albedoTexture.animations&&this._albedoTexture.animations.length>0&&e.push(this._albedoTexture),this._ambientTexture&&this._ambientTexture.animations&&this._ambientTexture.animations.length>0&&e.push(this._ambientTexture),this._opacityTexture&&this._opacityTexture.animations&&this._opacityTexture.animations.length>0&&e.push(this._opacityTexture),this._reflectionTexture&&this._reflectionTexture.animations&&this._reflectionTexture.animations.length>0&&e.push(this._reflectionTexture),this._emissiveTexture&&this._emissiveTexture.animations&&this._emissiveTexture.animations.length>0&&e.push(this._emissiveTexture),this._metallicTexture&&this._metallicTexture.animations&&this._metallicTexture.animations.length>0?e.push(this._metallicTexture):this._reflectivityTexture&&this._reflectivityTexture.animations&&this._reflectivityTexture.animations.length>0&&e.push(this._reflectivityTexture),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._lightmapTexture&&this._lightmapTexture.animations&&this._lightmapTexture.animations.length>0&&e.push(this._lightmapTexture),this._metallicReflectanceTexture&&this._metallicReflectanceTexture.animations&&this._metallicReflectanceTexture.animations.length>0&&e.push(this._metallicReflectanceTexture),this._reflectanceTexture&&this._reflectanceTexture.animations&&this._reflectanceTexture.animations.length>0&&e.push(this._reflectanceTexture),this._microSurfaceTexture&&this._microSurfaceTexture.animations&&this._microSurfaceTexture.animations.length>0&&e.push(this._microSurfaceTexture),e}_getReflectionTexture(){return this._reflectionTexture?this._reflectionTexture:this.getScene().environmentTexture}getActiveTextures(){const e=super.getActiveTextures();return this._albedoTexture&&e.push(this._albedoTexture),this._ambientTexture&&e.push(this._ambientTexture),this._opacityTexture&&e.push(this._opacityTexture),this._reflectionTexture&&e.push(this._reflectionTexture),this._emissiveTexture&&e.push(this._emissiveTexture),this._reflectivityTexture&&e.push(this._reflectivityTexture),this._metallicTexture&&e.push(this._metallicTexture),this._metallicReflectanceTexture&&e.push(this._metallicReflectanceTexture),this._reflectanceTexture&&e.push(this._reflectanceTexture),this._microSurfaceTexture&&e.push(this._microSurfaceTexture),this._bumpTexture&&e.push(this._bumpTexture),this._lightmapTexture&&e.push(this._lightmapTexture),e}hasTexture(e){return!!super.hasTexture(e)||(this._albedoTexture===e||(this._ambientTexture===e||(this._opacityTexture===e||(this._reflectionTexture===e||(this._emissiveTexture===e||(this._reflectivityTexture===e||(this._metallicTexture===e||(this._metallicReflectanceTexture===e||(this._reflectanceTexture===e||(this._microSurfaceTexture===e||(this._bumpTexture===e||this._lightmapTexture===e)))))))))))}setPrePassRenderer(){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)}}Xs.PBRMATERIAL_OPAQUE=Ji.MATERIAL_OPAQUE,Xs.PBRMATERIAL_ALPHATEST=Ji.MATERIAL_ALPHATEST,Xs.PBRMATERIAL_ALPHABLEND=Ji.MATERIAL_ALPHABLEND,Xs.PBRMATERIAL_ALPHATESTANDBLEND=Ji.MATERIAL_ALPHATESTANDBLEND,Xs.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=0,Xs.LIGHTFALLOFF_PHYSICAL=0,Xs.LIGHTFALLOFF_GLTF=1,Xs.LIGHTFALLOFF_STANDARD=2,Xs.ForceGLSL=!1,e([function(e){return r(9,e)}()],Xs.prototype,"_imageProcessingConfiguration",void 0),e([s("_markAllSubMeshesAsMiscDirty")],Xs.prototype,"debugMode",void 0);class Hs extends Xs{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===Xs.LIGHTFALLOFF_PHYSICAL}set usePhysicalLightFalloff(e){e!==this.usePhysicalLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),this._lightFalloff=e?Xs.LIGHTFALLOFF_PHYSICAL:Xs.LIGHTFALLOFF_STANDARD)}get useGLTFLightFalloff(){return this._lightFalloff===Xs.LIGHTFALLOFF_GLTF}set useGLTFLightFalloff(e){e!==this.useGLTFLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),this._lightFalloff=e?Xs.LIGHTFALLOFF_GLTF:Xs.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=Hs.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,this.metallicF0Factor=1,this.metallicReflectanceColor=ee.White(),this.useOnlyMetallicFromMetallicReflectanceTexture=!1,this.ambientColor=new ee(0,0,0),this.albedoColor=new ee(1,1,1),this.reflectivityColor=new ee(1,1,1),this.reflectionColor=new ee(1,1,1),this.emissiveColor=new ee(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=os(this.getScene())}getClassName(){return"PBRMaterial"}clone(e,t=!0,i=""){const n=re.Clone((()=>new Hs(e,this.getScene())),this,{cloneTexturesOnlyOnce:t});return n.id=e,n.name=e,this.stencil.copyTo(n.stencil),this._clonePlugins(n,i),n}serialize(){const e=super.serialize();return e.customType="BABYLON.PBRMaterial",e}static Parse(e,t,i){const n=re.Parse((()=>new Hs(e.name,t)),e,t,i);return e.stencil&&n.stencil.parse(e.stencil,t,i),Ji._ParsePlugins(e,n,t,i),e.clearCoat&&n.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&n.anisotropy.parse(e.anisotropy,t,i),e.brdf&&n.brdf.parse(e.brdf,t,i),e.sheen&&n.sheen.parse(e.sheen,t,i),e.subSurface&&n.subSurface.parse(e.subSurface,t,i),e.iridescence&&n.iridescence.parse(e.iridescence,t,i),n}}Hs.PBRMATERIAL_OPAQUE=Xs.PBRMATERIAL_OPAQUE,Hs.PBRMATERIAL_ALPHATEST=Xs.PBRMATERIAL_ALPHATEST,Hs.PBRMATERIAL_ALPHABLEND=Xs.PBRMATERIAL_ALPHABLEND,Hs.PBRMATERIAL_ALPHATESTANDBLEND=Xs.PBRMATERIAL_ALPHATESTANDBLEND,Hs.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=Xs.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,e([a(),s("_markAllSubMeshesAsTexturesDirty")],Hs.prototype,"directIntensity",void 0),e([a(),s("_markAllSubMeshesAsTexturesDirty")],Hs.prototype,"emissiveIntensity",void 0),e([a(),s("_markAllSubMeshesAsTexturesDirty")],Hs.prototype,"environmentIntensity",void 0),e([a(),s("_markAllSubMeshesAsTexturesDirty")],Hs.prototype,"specularIntensity",void 0),e([a(),s("_markAllSubMeshesAsTexturesDirty")],Hs.prototype,"disableBumpMap",void 0),e([o(),s("_markAllSubMeshesAsTexturesDirty")],Hs.prototype,"albedoTexture",void 0),e([o(),s("_markAllSubMeshesAsTexturesDirty")],Hs.prototype,"ambientTexture",void 0),e([a(),s("_markAllSubMeshesAsTexturesDirty")],Hs.prototype,"ambientTextureStrength",void 0),e([a(),s("_markAllSubMeshesAsTexturesDirty")],Hs.prototype,"ambientTextureImpactOnAnalyticalLights",void 0),e([o(),s("_markAllSubMeshesAsTexturesAndMiscDirty")],Hs.prototype,"opacityTexture",void 0),e([o(),s("_markAllSubMeshesAsTexturesDirty")],Hs.prototype,"reflectionTexture",void 0),e([o(),s("_markAllSubMeshesAsTexturesDirty")],Hs.prototype,"emissiveTexture",void 0),e([o(),s("_markAllSubMeshesAsTexturesDirty")],Hs.prototype,"reflectivityTexture",void 0),e([o(),s("_markAllSubMeshesAsTexturesDirty")],Hs.prototype,"metallicTexture",void 0),e([a(),s("_markAllSubMeshesAsTexturesDirty")],Hs.prototype,"metallic",void 0),e([a(),s("_markAllSubMeshesAsTexturesDirty")],Hs.prototype,"roughness",void 0),e([a(),s("_markAllSubMeshesAsTexturesDirty")],Hs.prototype,"metallicF0Factor",void 0),e([l(),s("_markAllSubMeshesAsTexturesDirty")],Hs.prototype,"metallicReflectanceColor",void 0),e([a(),s("_markAllSubMeshesAsTexturesDirty")],Hs.prototype,"useOnlyMetallicFromMetallicReflectanceTexture",void 0),e([o(),s("_markAllSubMeshesAsTexturesDirty")],Hs.prototype,"metallicReflectanceTexture",void 0),e([o(),s("_markAllSubMeshesAsTexturesDirty")],Hs.prototype,"reflectanceTexture",void 0),e([o(),s("_markAllSubMeshesAsTexturesDirty")],Hs.prototype,"microSurfaceTexture",void 0),e([o(),s("_markAllSubMeshesAsTexturesDirty")],Hs.prototype,"bumpTexture",void 0),e([o(),s("_markAllSubMeshesAsTexturesDirty",null)],Hs.prototype,"lightmapTexture",void 0),e([l("ambient"),s("_markAllSubMeshesAsTexturesDirty")],Hs.prototype,"ambientColor",void 0),e([l("albedo"),s("_markAllSubMeshesAsTexturesDirty")],Hs.prototype,"albedoColor",void 0),e([l("reflectivity"),s("_markAllSubMeshesAsTexturesDirty")],Hs.prototype,"reflectivityColor",void 0),e([l("reflection"),s("_markAllSubMeshesAsTexturesDirty")],Hs.prototype,"reflectionColor",void 0),e([l("emissive"),s("_markAllSubMeshesAsTexturesDirty")],Hs.prototype,"emissiveColor",void 0),e([a(),s("_markAllSubMeshesAsTexturesDirty")],Hs.prototype,"microSurface",void 0),e([a(),s("_markAllSubMeshesAsTexturesDirty")],Hs.prototype,"useLightmapAsShadowmap",void 0),e([a(),s("_markAllSubMeshesAsTexturesAndMiscDirty")],Hs.prototype,"useAlphaFromAlbedoTexture",void 0),e([a(),s("_markAllSubMeshesAsTexturesAndMiscDirty")],Hs.prototype,"forceAlphaTest",void 0),e([a(),s("_markAllSubMeshesAsTexturesAndMiscDirty")],Hs.prototype,"alphaCutOff",void 0),e([a(),s("_markAllSubMeshesAsTexturesDirty")],Hs.prototype,"useSpecularOverAlpha",void 0),e([a(),s("_markAllSubMeshesAsTexturesDirty")],Hs.prototype,"useMicroSurfaceFromReflectivityMapAlpha",void 0),e([a(),s("_markAllSubMeshesAsTexturesDirty")],Hs.prototype,"useRoughnessFromMetallicTextureAlpha",void 0),e([a(),s("_markAllSubMeshesAsTexturesDirty")],Hs.prototype,"useRoughnessFromMetallicTextureGreen",void 0),e([a(),s("_markAllSubMeshesAsTexturesDirty")],Hs.prototype,"useMetallnessFromMetallicTextureBlue",void 0),e([a(),s("_markAllSubMeshesAsTexturesDirty")],Hs.prototype,"useAmbientOcclusionFromMetallicTextureRed",void 0),e([a(),s("_markAllSubMeshesAsTexturesDirty")],Hs.prototype,"useAmbientInGrayScale",void 0),e([a(),s("_markAllSubMeshesAsTexturesDirty")],Hs.prototype,"useAutoMicroSurfaceFromReflectivityMap",void 0),e([a()],Hs.prototype,"usePhysicalLightFalloff",null),e([a()],Hs.prototype,"useGLTFLightFalloff",null),e([a(),s("_markAllSubMeshesAsTexturesDirty")],Hs.prototype,"useRadianceOverAlpha",void 0),e([a(),s("_markAllSubMeshesAsTexturesDirty")],Hs.prototype,"useObjectSpaceNormalMap",void 0),e([a(),s("_markAllSubMeshesAsTexturesDirty")],Hs.prototype,"useParallax",void 0),e([a(),s("_markAllSubMeshesAsTexturesDirty")],Hs.prototype,"useParallaxOcclusion",void 0),e([a(),s("_markAllSubMeshesAsTexturesDirty")],Hs.prototype,"parallaxScaleBias",void 0),e([a(),s("_markAllSubMeshesAsLightsDirty")],Hs.prototype,"disableLighting",void 0),e([a(),s("_markAllSubMeshesAsTexturesDirty")],Hs.prototype,"forceIrradianceInFragment",void 0),e([a(),s("_markAllSubMeshesAsLightsDirty")],Hs.prototype,"maxSimultaneousLights",void 0),e([a(),s("_markAllSubMeshesAsTexturesDirty")],Hs.prototype,"invertNormalMapX",void 0),e([a(),s("_markAllSubMeshesAsTexturesDirty")],Hs.prototype,"invertNormalMapY",void 0),e([a(),s("_markAllSubMeshesAsTexturesDirty")],Hs.prototype,"twoSidedLighting",void 0),e([a(),s("_markAllSubMeshesAsTexturesDirty")],Hs.prototype,"useAlphaFresnel",void 0),e([a(),s("_markAllSubMeshesAsTexturesDirty")],Hs.prototype,"useLinearAlphaFresnel",void 0),e([s("_markAllSubMeshesAsTexturesDirty")],Hs.prototype,"environmentBRDFTexture",void 0),e([a(),s("_markAllSubMeshesAsTexturesDirty")],Hs.prototype,"forceNormalForward",void 0),e([a(),s("_markAllSubMeshesAsTexturesDirty")],Hs.prototype,"enableSpecularAntiAliasing",void 0),e([a(),s("_markAllSubMeshesAsTexturesDirty")],Hs.prototype,"useHorizonOcclusion",void 0),e([a(),s("_markAllSubMeshesAsTexturesDirty")],Hs.prototype,"useRadianceOcclusion",void 0),e([a(),s("_markAllSubMeshesAsMiscDirty")],Hs.prototype,"unlit",void 0),e([a(),s("_markAllSubMeshesAsMiscDirty")],Hs.prototype,"applyDecalMapAfterDetailMap",void 0),M("BABYLON.PBRMaterial",Hs),vt.prototype._partialLoadFile=function(e,t,i,n,r=null){this._loadFile(e,(e=>{i[t]=e,i._internalCount++,6===i._internalCount&&n(i)}),void 0,void 0,!0,((e,t)=>{r&&e&&r(e.status+" "+e.statusText,t)}))},vt.prototype._cascadeLoadFiles=function(e,t,i,n=null){const r=[];r._internalCount=0;for(let e=0;e<6;e++)this._partialLoadFile(i[e],e,r,t,n)},vt.prototype._cascadeLoadImgs=function(e,t,i,n,r=null,s){const a=[];a._internalCount=0;for(let o=0;o<6;o++)this._partialLoadImg(n[o],o,a,e,t,i,r,s)},vt.prototype._partialLoadImg=function(e,t,i,n,r,s,a=null,o){const l=Gt();bt(e,(e=>{i[t]=e,i._internalCount++,n&&n.removePendingData(l),6===i._internalCount&&s&&s(r,i)}),((e,t)=>{n&&n.removePendingData(l),a&&a(e,t)}),n?n.offlineProvider:null,o),n&&n.addPendingData(l)},vt.prototype.createCubeTextureBase=function(e,t,i,n,r=null,s=null,a,o=null,l=!1,c=0,h=0,d=null,u=null,f=null,_=!1,m=null){const p=d||new Et(this,7);p.isCube=!0,p.url=e,p.generateMipMaps=!n,p._lodGenerationScale=c,p._lodGenerationOffset=h,p._useSRGBBuffer=!!_&&this._caps.supportSRGBBuffers&&(this.version>1||this.isWebGPU||!!n),p!==d&&(p.label=e.substring(0,60)),this._doNotHandleContextLost||(p._extension=o,p._files=i,p._buffer=m);const g=e;this._transformTextureUrl&&!d&&(e=this._transformTextureUrl(e));const E=e.split("?")[0],T=E.lastIndexOf("."),A=Tt(o||(T>-1?E.substring(T).toLowerCase():"")),v=(d,E)=>{e===g?s&&d&&s(d.status+" "+d.statusText,E):(de.Warn(`Failed to load ${e}, falling back to the ${g}`),this.createCubeTextureBase(g,t,i,!!n,r,s,a,o,l,c,h,p,u,f,_,m))};if(A)A.then((n=>{const a=e=>{u&&u(p,e),n.loadCubeData(e,p,l,r,s)};m?a(m):i&&6===i.length?n.supportCascades?this._cascadeLoadFiles(t,(e=>a(e.map((e=>new Uint8Array(e))))),i,s):s?s("Textures type does not support cascades."):de.Warn("Texture loader does not support cascades."):this._loadFile(e,(e=>a(new Uint8Array(e))),void 0,void 0,!0,v)}));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,p,((e,t)=>{f&&f(e,t)}),i,s)}return this._internalTexturesCache.push(p),p},Ni.prototype._createDepthStencilCubeTexture=function(e,t){const i=new Et(this,12);if(i.isCube=!0,1===this.webGLVersion)return de.Error("Depth cube texture is not supported by WebGL 1."),i;const n={bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,...t},r=this._gl;this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,i,!0),this._setupDepthStencilTexture(i,e,n.generateStencil,n.bilinearFiltering,n.comparisonFunction);for(let t=0;t<6;t++)n.generateStencil?r.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,r.DEPTH24_STENCIL8,e,e,0,r.DEPTH_STENCIL,r.UNSIGNED_INT_24_8,null):r.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,r.DEPTH_COMPONENT24,e,e,0,r.DEPTH_COMPONENT,r.UNSIGNED_INT,null);return this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,null),this._internalTexturesCache.push(i),i},Ni.prototype._setCubeMapTextureParams=function(e,t,i){const n=this._gl;n.texParameteri(n.TEXTURE_CUBE_MAP,n.TEXTURE_MAG_FILTER,n.LINEAR),n.texParameteri(n.TEXTURE_CUBE_MAP,n.TEXTURE_MIN_FILTER,t?n.LINEAR_MIPMAP_LINEAR:n.LINEAR),n.texParameteri(n.TEXTURE_CUBE_MAP,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_CUBE_MAP,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE),e.samplingMode=t?Ze.TEXTURE_TRILINEAR_SAMPLINGMODE:Ze.TEXTURE_LINEAR_LINEAR,t&&this.getCaps().textureMaxLevel&&void 0!==i&&i>0&&(n.texParameteri(n.TEXTURE_CUBE_MAP,n.TEXTURE_MAX_LEVEL,i),e._maxLodLevel=i),this._bindTextureDirectly(n.TEXTURE_CUBE_MAP,null)},Ni.prototype.createCubeTexture=function(e,t,i,n,r=null,s=null,a,o=null,l=!1,c=0,h=0,d=null,u,f=!1,_=null){const m=this._gl;return this.createCubeTextureBase(e,t,i,!!n,r,s,a,o,l,c,h,d,(e=>this._bindTextureDirectly(m.TEXTURE_CUBE_MAP,e,!0)),((e,t)=>{const i=this.needPOTTextures?zt(t[0].width,this._caps.maxCubemapTextureSize):t[0].width,s=i,o=[m.TEXTURE_CUBE_MAP_POSITIVE_X,m.TEXTURE_CUBE_MAP_POSITIVE_Y,m.TEXTURE_CUBE_MAP_POSITIVE_Z,m.TEXTURE_CUBE_MAP_NEGATIVE_X,m.TEXTURE_CUBE_MAP_NEGATIVE_Y,m.TEXTURE_CUBE_MAP_NEGATIVE_Z];this._bindTextureDirectly(m.TEXTURE_CUBE_MAP,e,!0),this._unpackFlipY(!1);const l=a?this._getInternalFormat(a,e._useSRGBBuffer):e._useSRGBBuffer?this._glSRGBExtensionValues.SRGB8_ALPHA8:m.RGBA;let c=a?this._getInternalFormat(a):m.RGBA;e._useSRGBBuffer&&1===this.webGLVersion&&(c=l);for(let e=0;e<o.length;e++)if(t[e].width!==i||t[e].height!==s){if(this._prepareWorkingCanvas(),!this._workingCanvas||!this._workingContext)return void de.Warn("Cannot create canvas to resize texture.");this._workingCanvas.width=i,this._workingCanvas.height=s,this._workingContext.drawImage(t[e],0,0,t[e].width,t[e].height,0,0,i,s),m.texImage2D(o[e],0,l,c,m.UNSIGNED_BYTE,this._workingCanvas)}else m.texImage2D(o[e],0,l,c,m.UNSIGNED_BYTE,t[e]);n||m.generateMipmap(m.TEXTURE_CUBE_MAP),this._setCubeMapTextureParams(e,!n),e.width=i,e.height=s,e.isReady=!0,a&&(e.format=a),e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear(),r&&r()}),!!f,_)},Ni.prototype.generateMipMapsForCubemap=function(e,t=!0){if(e.generateMipMaps){const i=this._gl;this._bindTextureDirectly(i.TEXTURE_CUBE_MAP,e,!0),i.generateMipmap(i.TEXTURE_CUBE_MAP),t&&this._bindTextureDirectly(i.TEXTURE_CUBE_MAP,null)}};const Ws=131072,zs=131072;function Ys(e){return e.charCodeAt(0)+(e.charCodeAt(1)<<8)+(e.charCodeAt(2)<<16)+(e.charCodeAt(3)<<24)}const Ks=Ys("DXT1"),qs=Ys("DXT3"),js=Ys("DXT5"),Qs=Ys("DX10");class Zs{static GetDDSInfo(e){const t=new Int32Array(e.buffer,e.byteOffset,31),i=new Int32Array(e.buffer,e.byteOffset,35);let n=1;t[2]&Ws&&(n=Math.max(1,t[7]));const r=t[21],s=r===Qs?i[32]:0;let a=Ze.TEXTURETYPE_UNSIGNED_INT;switch(r){case 113:a=Ze.TEXTURETYPE_HALF_FLOAT;break;case 116:a=Ze.TEXTURETYPE_FLOAT;break;case Qs:if(10===s){a=Ze.TEXTURETYPE_HALF_FLOAT;break}if(2===s){a=Ze.TEXTURETYPE_FLOAT;break}}return{width:t[4],height:t[3],mipmapCount:n,isFourCC:!(4&~t[20]),isRGB:!(64&~t[20]),isLuminance:(t[20]&zs)===zs,isCube:!(512&~t[28]),isCompressed:r===Ks||r===qs||r===js,dxgiFormat:s,textureType:a}}static _GetHalfFloatAsFloatRGBAArrayBuffer(e,t,i,n,r,s){const a=new Float32Array(n),o=new Uint16Array(r,i);let l=0;for(let i=0;i<t;i++)for(let t=0;t<e;t++){const n=4*(t+i*e);a[l]=rs(o[n]),a[l+1]=rs(o[n+1]),a[l+2]=rs(o[n+2]),Zs.StoreLODInAlphaChannel?a[l+3]=s:a[l+3]=rs(o[n+3]),l+=4}return a}static _GetHalfFloatRGBAArrayBuffer(e,t,i,n,r,s){if(Zs.StoreLODInAlphaChannel){const a=new Uint16Array(n),o=new Uint16Array(r,i);let l=0;for(let i=0;i<t;i++)for(let t=0;t<e;t++){const n=4*(t+i*e);a[l]=o[n],a[l+1]=o[n+1],a[l+2]=o[n+2],a[l+3]=ns(s),l+=4}return a}return new Uint16Array(r,i,n)}static _GetFloatRGBAArrayBuffer(e,t,i,n,r,s){if(Zs.StoreLODInAlphaChannel){const a=new Float32Array(n),o=new Float32Array(r,i);let l=0;for(let i=0;i<t;i++)for(let t=0;t<e;t++){const n=4*(t+i*e);a[l]=o[n],a[l+1]=o[n+1],a[l+2]=o[n+2],a[l+3]=s,l+=4}return a}return new Float32Array(r,i,n)}static _GetFloatAsHalfFloatRGBAArrayBuffer(e,t,i,n,r,s){const a=new Uint16Array(n),o=new Float32Array(r,i);let l=0;for(let i=0;i<t;i++)for(let t=0;t<e;t++)a[l]=ns(o[l]),a[l+1]=ns(o[l+1]),a[l+2]=ns(o[l+2]),Zs.StoreLODInAlphaChannel?a[l+3]=ns(s):a[l+3]=ns(o[l+3]),l+=4;return a}static _GetFloatAsUIntRGBAArrayBuffer(e,t,i,n,r,s){const a=new Uint8Array(n),o=new Float32Array(r,i);let l=0;for(let i=0;i<t;i++)for(let t=0;t<e;t++){const n=4*(t+i*e);a[l]=255*j.Clamp(o[n]),a[l+1]=255*j.Clamp(o[n+1]),a[l+2]=255*j.Clamp(o[n+2]),Zs.StoreLODInAlphaChannel?a[l+3]=s:a[l+3]=255*j.Clamp(o[n+3]),l+=4}return a}static _GetHalfFloatAsUIntRGBAArrayBuffer(e,t,i,n,r,s){const a=new Uint8Array(n),o=new Uint16Array(r,i);let l=0;for(let i=0;i<t;i++)for(let t=0;t<e;t++){const n=4*(t+i*e);a[l]=255*j.Clamp(rs(o[n])),a[l+1]=255*j.Clamp(rs(o[n+1])),a[l+2]=255*j.Clamp(rs(o[n+2])),Zs.StoreLODInAlphaChannel?a[l+3]=s:a[l+3]=255*j.Clamp(rs(o[n+3])),l+=4}return a}static _GetRGBAArrayBuffer(e,t,i,n,r,s,a,o,l){const c=new Uint8Array(n),h=new Uint8Array(r,i);let d=0;for(let i=0;i<t;i++)for(let t=0;t<e;t++){const n=4*(t+i*e);c[d]=h[n+s],c[d+1]=h[n+a],c[d+2]=h[n+o],c[d+3]=h[n+l],d+=4}return c}static _ExtractLongWordOrder(e){return 0===e||255===e||-16777216===e?0:1+Zs._ExtractLongWordOrder(e>>8)}static _GetRGBArrayBuffer(e,t,i,n,r,s,a,o){const l=new Uint8Array(n),c=new Uint8Array(r,i);let h=0;for(let i=0;i<t;i++)for(let t=0;t<e;t++){const n=3*(t+i*e);l[h]=c[n+s],l[h+1]=c[n+a],l[h+2]=c[n+o],h+=3}return l}static _GetLuminanceArrayBuffer(e,t,i,n,r){const s=new Uint8Array(n),a=new Uint8Array(r,i);let o=0;for(let i=0;i<t;i++)for(let t=0;t<e;t++){const n=t+i*e;s[o]=a[n],o++}return s}static UploadDDSLevels(e,t,i,n,r,s,a=-1,o,l=!0){let c=null;n.sphericalPolynomial&&(c=[]);const h=!!e.getCaps().s3tc;t.generateMipMaps=r;const d=new Int32Array(i.buffer,i.byteOffset,31);let u,f,_,m,p,g,E,T=0,A=0,v=1;if(542327876!==d[0])return void de.Error("Invalid magic number in DDS header");if(!n.isFourCC&&!n.isRGB&&!n.isLuminance)return void de.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");if(n.isCompressed&&!h)return void de.Error("Compressed textures are not supported on this platform.");let R=d[22];m=d[1]+4;let S=!1;if(n.isFourCC)switch(u=d[21],u){case Ks:v=8,A=Ze.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT1;break;case qs:v=16,A=Ze.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT3;break;case js:v=16,A=Ze.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT5;break;case 113:S=!0,R=64;break;case 116:S=!0,R=128;break;case Qs:{m+=20;let e=!1;switch(n.dxgiFormat){case 10:S=!0,R=64,e=!0;break;case 2:S=!0,R=128,e=!0;break;case 88:n.isRGB=!0,n.isFourCC=!1,R=32,e=!0}if(e)break}default:return void de.Error(["Unsupported FourCC code:",(I=u,String.fromCharCode(255&I,I>>8&255,I>>16&255,I>>24&255))])}var I;const C=Zs._ExtractLongWordOrder(d[23]),M=Zs._ExtractLongWordOrder(d[24]),x=Zs._ExtractLongWordOrder(d[25]),b=Zs._ExtractLongWordOrder(d[26]);S&&(A=e._getRGBABufferInternalSizedFormat(n.textureType)),g=1,d[2]&Ws&&!1!==r&&(g=Math.max(1,d[7]));const y=o||0,O=e.getCaps();for(let r=y;r<s;r++){for(f=d[4],_=d[3],E=0;E<g;++E){if(-1===a||a===E){const s=-1===a?E:0;if(!n.isCompressed&&n.isFourCC){t.format=Ze.TEXTUREFORMAT_RGBA,T=f*_*4;let n=null;if(e._badOS||e._badDesktopOS||!O.textureHalfFloat&&!O.textureFloat)128===R?(n=Zs._GetFloatAsUIntRGBAArrayBuffer(f,_,i.byteOffset+m,T,i.buffer,s),c&&0==s&&c.push(Zs._GetFloatRGBAArrayBuffer(f,_,i.byteOffset+m,T,i.buffer,s))):64===R&&(n=Zs._GetHalfFloatAsUIntRGBAArrayBuffer(f,_,i.byteOffset+m,T,i.buffer,s),c&&0==s&&c.push(Zs._GetHalfFloatAsFloatRGBAArrayBuffer(f,_,i.byteOffset+m,T,i.buffer,s))),t.type=Ze.TEXTURETYPE_UNSIGNED_INT;else{const e=O.textureFloat&&(l&&O.textureFloatLinearFiltering||!l),r=O.textureHalfFloat&&(l&&O.textureHalfFloatLinearFiltering||!l),a=(128===R||64===R&&!r)&&e?Ze.TEXTURETYPE_FLOAT:(64===R||128===R&&!e)&&r?Ze.TEXTURETYPE_HALF_FLOAT:Ze.TEXTURETYPE_UNSIGNED_BYTE;let o,h=null;if(128===R)switch(a){case Ze.TEXTURETYPE_FLOAT:o=Zs._GetFloatRGBAArrayBuffer,h=null;break;case Ze.TEXTURETYPE_HALF_FLOAT:o=Zs._GetFloatAsHalfFloatRGBAArrayBuffer,h=Zs._GetFloatRGBAArrayBuffer;break;case Ze.TEXTURETYPE_UNSIGNED_BYTE:o=Zs._GetFloatAsUIntRGBAArrayBuffer,h=Zs._GetFloatRGBAArrayBuffer}else switch(a){case Ze.TEXTURETYPE_FLOAT:o=Zs._GetHalfFloatAsFloatRGBAArrayBuffer,h=null;break;case Ze.TEXTURETYPE_HALF_FLOAT:o=Zs._GetHalfFloatRGBAArrayBuffer,h=Zs._GetHalfFloatAsFloatRGBAArrayBuffer;break;case Ze.TEXTURETYPE_UNSIGNED_BYTE:o=Zs._GetHalfFloatAsUIntRGBAArrayBuffer,h=Zs._GetHalfFloatAsFloatRGBAArrayBuffer}t.type=a,n=o(f,_,i.byteOffset+m,T,i.buffer,s),c&&0==s&&c.push(h?h(f,_,i.byteOffset+m,T,i.buffer,s):n)}n&&e._uploadDataToTextureDirectly(t,n,r,s)}else if(n.isRGB)t.type=Ze.TEXTURETYPE_UNSIGNED_INT,24===R?(t.format=Ze.TEXTUREFORMAT_RGB,T=f*_*3,p=Zs._GetRGBArrayBuffer(f,_,i.byteOffset+m,T,i.buffer,C,M,x),e._uploadDataToTextureDirectly(t,p,r,s)):(t.format=Ze.TEXTUREFORMAT_RGBA,T=f*_*4,p=Zs._GetRGBAArrayBuffer(f,_,i.byteOffset+m,T,i.buffer,C,M,x,b),e._uploadDataToTextureDirectly(t,p,r,s));else if(n.isLuminance){const n=e._getUnpackAlignement(),a=f;T=Math.floor((f+n-1)/n)*n*(_-1)+a,p=Zs._GetLuminanceArrayBuffer(f,_,i.byteOffset+m,T,i.buffer),t.format=Ze.TEXTUREFORMAT_LUMINANCE,t.type=Ze.TEXTURETYPE_UNSIGNED_INT,e._uploadDataToTextureDirectly(t,p,r,s)}else T=Math.max(4,f)/4*Math.max(4,_)/4*v,p=new Uint8Array(i.buffer,i.byteOffset+m,T),t.type=Ze.TEXTURETYPE_UNSIGNED_INT,e._uploadCompressedDataToTextureDirectly(t,A,f,_,p,r,s)}m+=R?f*_*(R/8):T,f*=.5,_*=.5,f=Math.max(1,f),_=Math.max(1,_)}if(void 0!==o)break}c&&c.length>0?n.sphericalPolynomial=Ms.ConvertCubeMapToSphericalPolynomial({size:d[4],right:c[0],left:c[1],up:c[2],down:c[3],front:c[4],back:c[5],format:Ze.TEXTUREFORMAT_RGBA,type:Ze.TEXTURETYPE_FLOAT,gammaSpace:!1}):n.sphericalPolynomial=void 0}}Zs.StoreLODInAlphaChannel=!1,Ni.prototype.createPrefilteredCubeTexture=function(e,t,i,n,r=null,s=null,a,o=null,l=!0){return this.createCubeTexture(e,t,null,!1,(e=>{if(!e)return void(r&&r(null));const s=e.texture;if(l?e.info.sphericalPolynomial&&(s._sphericalPolynomial=e.info.sphericalPolynomial):s._sphericalPolynomial=new Is,s._source=9,this.getCaps().textureLOD)return void(r&&r(s));const a=this._gl,o=e.width;if(!o)return;const c=[];for(let r=0;r<3;r++){const l=1-r/2,h=n,d=j.Log2(o)*i+n,u=h+(d-h)*l,f=Math.round(Math.min(Math.max(u,0),d)),_=new Et(this,2);if(_.type=s.type,_.format=s.format,_.width=Math.pow(2,Math.max(j.Log2(o)-f,0)),_.height=_.width,_.isCube=!0,_._cachedWrapU=Ze.TEXTURE_CLAMP_ADDRESSMODE,_._cachedWrapV=Ze.TEXTURE_CLAMP_ADDRESSMODE,this._bindTextureDirectly(a.TEXTURE_CUBE_MAP,_,!0),_.samplingMode=Ze.TEXTURE_LINEAR_LINEAR,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),Zs.UploadDDSLevels(this,_,i,t,!0,6,f)}else de.Warn("DDS is the only prefiltered cube map supported so far.");this._bindTextureDirectly(a.TEXTURE_CUBE_MAP,null);const m=new Dr(t);m._isCube=!0,m._texture=_,_.isReady=!0,c.push(m)}s._lodTextureHigh=c[2],s._lodTextureMid=c[1],s._lodTextureLow=c[0],r&&r(s)}),s,a,o,l,i,n)};class Js extends Dr{set boundingBoxSize(e){if(this._boundingBoxSize&&this._boundingBoxSize.equals(e))return;this._boundingBoxSize=e;const t=this.getScene();t&&t.markAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag)}get boundingBoxSize(){return this._boundingBoxSize}set rotationY(e){this._rotationY=e,this.setReflectionTextureMatrix(k.RotationY(this._rotationY))}get rotationY(){return this._rotationY}get noMipmap(){return this._noMipmap}get forcedExtension(){return this._forcedExtension}static CreateFromImages(e,t,i){let n="";return e.forEach((e=>n+=e)),new Js(n,t,null,i,e)}static CreateFromPrefilteredData(e,t,i=null,n=!0){const r=t.useDelayedTextureLoading;t.useDelayedTextureLoading=!1;const s=new Js(e,t,null,!1,null,null,null,void 0,!0,i,n);return t.useDelayedTextureLoading=r,s}constructor(e,t,i=null,n=!1,r=null,s=null,a=null,o=Ze.TEXTUREFORMAT_RGBA,l=!1,c=null,h=!1,d=.8,u=0,f,_){super(t),this.onLoadObservable=new g,this.boundingBoxPosition=B.Zero(),this._rotationY=0,this._files=null,this._forcedExtension=null,this._extensions=null,this._textureMatrixRefraction=new k,this._buffer=null,this.name=e,this.url=e,this._noMipmap=n,this.hasAlpha=!1,this.isCube=!0,this._textureMatrix=k.Identity(),this.coordinatesMode=Pr.CUBIC_MODE;let m=null,p=null;null===i||Array.isArray(i)?(this._noMipmap=n,this._format=o,this._createPolynomials=h,m=i,this._loaderOptions=f,this._useSRGBBuffer=_,this._lodScale=d,this._lodOffset=u):(m=i.extensions??null,this._noMipmap=i.noMipmap??!1,r=i.files??null,p=i.buffer??null,this._format=i.format??Ze.TEXTUREFORMAT_RGBA,l=i.prefiltered??!1,c=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,s=i.onLoad??null,a=i.onError??null),(e||r)&&this.updateURL(e,c,s,l,a,m,this.getScene()?.useDelayedTextureLoading,r,p)}getClassName(){return"CubeTexture"}updateURL(e,t=null,i=null,n=!1,r=null,s=null,a=!1,o=null,l=null){this.name&&!this.name.startsWith("data:")||(this.name=e),this.url=e,t&&(this._forcedExtension=t);const c=e.lastIndexOf("."),h=t||(c>-1?e.substring(c).toLowerCase():""),d=0===h.indexOf(".dds"),u=0===h.indexOf(".env"),f=0===h.indexOf(".basis");if(u?(this.gammaSpace=!1,this._prefiltered=!1,this.anisotropicFilteringLevel=1):(this._prefiltered=n,n&&(this.gammaSpace=!1,this.anisotropicFilteringLevel=1)),o)this._files=o;else if(f||u||d||s||(s=["_px.jpg","_py.jpg","_pz.jpg","_nx.jpg","_ny.jpg","_nz.jpg"]),this._files=this._files||[],this._files.length=0,s){for(let t=0;t<s.length;t++)this._files.push(e+s[t]);this._extensions=s}this._buffer=l,a?(this.delayLoadState=Ze.DELAYLOADSTATE_NOTLOADED,this._delayedOnLoad=i,this._delayedOnError=r):this._loadTexture(i,r)}delayLoad(e){this.delayLoadState===Ze.DELAYLOADSTATE_NOTLOADED&&(e&&(this._forcedExtension=e),this.delayLoadState=Ze.DELAYLOADSTATE_LOADED,this._loadTexture(this._delayedOnLoad,this._delayedOnError))}getReflectionTextureMatrix(){return this._textureMatrix}setReflectionTextureMatrix(e){if(e.updateFlag===this._textureMatrix.updateFlag)return;if(e.isIdentity()!==this._textureMatrix.isIdentity()&&this.getScene()?.markAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag,(e=>-1!==e.getActiveTextures().indexOf(this))),this._textureMatrix=e,!this.getScene()?.useRightHandedSystem)return;const t=H.Vector3[0],i=H.Quaternion[0],n=H.Vector3[1];this._textureMatrix.decompose(t,i,n),i.z*=-1,i.w*=-1,k.ComposeToRef(t,i,n,this._textureMatrixRefraction)}getRefractionTextureMatrix(){return this.getScene()?.useRightHandedSystem?this._textureMatrixRefraction:this._textureMatrix}_loadTexture(e=null,t=null){const i=this.getScene(),n=this._texture;this._texture=this._getFromCache(this.url,this._noMipmap,void 0,void 0,this._useSRGBBuffer,this.isCube);const r=()=>{this.onLoadObservable.notifyObservers(this),n&&(n.dispose(),this.getScene()?.markAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag)),e&&e()},s=(e,i)=>{this._loadingError=!0,this._errorObject={message:e,exception:i},t&&t(e,i),Pr.OnTextureLoadErrorObservable.notifyObservers(this)};this._texture?this._texture.isReady?Yt.SetImmediate((()=>r())):this._texture.onLoadedObservable.add((()=>r())):(this._prefiltered?this._texture=this._getEngine().createPrefilteredCubeTexture(this.url,i,this._lodScale,this._lodOffset,e,s,this._format,this._forcedExtension,this._createPolynomials):this._texture=this._getEngine().createCubeTexture(this.url,i,this._files,this._noMipmap,e,s,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 n=re.Parse((()=>{let n=!1;return e.prefiltered&&(n=e.prefiltered),new Js(i+(e.url??e.name),t,e.extensions,!1,e.files||null,null,null,void 0,n,e.forcedExtension)}),e,t);if(e.boundingBoxPosition&&(n.boundingBoxPosition=B.FromArray(e.boundingBoxPosition)),e.boundingBoxSize&&(n.boundingBoxSize=B.FromArray(e.boundingBoxSize)),e.animations)for(let t=0;t<e.animations.length;t++){const i=e.animations[t],r=x("BABYLON.Animation");r&&n.animations.push(r.Parse(i))}return n}clone(){let e=0;const t=re.Clone((()=>{const t=new Js(this.url,this.getScene()||this._getEngine(),this._extensions,this._noMipmap,this._files);return e=t.uniqueId,t}),this);return t.uniqueId=e,t}}e([a()],Js.prototype,"url",void 0),e([h()],Js.prototype,"boundingBoxPosition",void 0),e([h()],Js.prototype,"boundingBoxSize",null),e([a("rotationY")],Js.prototype,"rotationY",null),e([a("files")],Js.prototype,"_files",void 0),e([a("forcedExtension")],Js.prototype,"_forcedExtension",void 0),e([a("extensions")],Js.prototype,"_extensions",void 0),e([f("textureMatrix")],Js.prototype,"_textureMatrix",void 0),e([f("textureMatrixRefraction")],Js.prototype,"_textureMatrixRefraction",void 0),Pr._CubeTextureParser=Js.Parse,M("BABYLON.CubeTexture",Js),ln._GroundMeshParser=(e,t)=>$s.Parse(e,t);class $s extends ln{constructor(e,t){super(e,t),this.generateOctree=!1}getClassName(){return"GroundMesh"}get subdivisions(){return Math.min(this._subdivisionsX,this._subdivisionsY)}get subdivisionsX(){return this._subdivisionsX}get subdivisionsY(){return this._subdivisionsY}optimize(e,t=32){this._subdivisionsX=e,this._subdivisionsY=e,this.subdivide(e);const i=this;i.createOrUpdateSubmeshesOctree&&i.createOrUpdateSubmeshesOctree(t)}getHeightAtCoordinates(e,t){const i=this.getWorldMatrix(),n=H.Matrix[5];i.invertToRef(n);const r=H.Vector3[8];if(B.TransformCoordinatesFromFloatsToRef(e,0,t,n,r),e=r.x,t=r.z,e<this._minX||e>=this._maxX||t<=this._minZ||t>this._maxZ)return this.position.y;this._heightQuads&&0!=this._heightQuads.length||(this._initHeightQuads(),this._computeHeightQuads());const s=this._getFacetAt(e,t),a=-(s.x*e+s.z*t+s.w)/s.y;return B.TransformCoordinatesFromFloatsToRef(0,a,0,i,r),r.y}getNormalAtCoordinates(e,t){const i=new B(0,1,0);return this.getNormalAtCoordinatesToRef(e,t,i),i}getNormalAtCoordinatesToRef(e,t,i){const n=this.getWorldMatrix(),r=H.Matrix[5];n.invertToRef(r);const s=H.Vector3[8];if(B.TransformCoordinatesFromFloatsToRef(e,0,t,r,s),e=s.x,t=s.z,e<this._minX||e>this._maxX||t<this._minZ||t>this._maxZ)return this;this._heightQuads&&0!=this._heightQuads.length||(this._initHeightQuads(),this._computeHeightQuads());const a=this._getFacetAt(e,t);return B.TransformNormalFromFloatsToRef(a.x,a.y,a.z,n,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),n=Math.floor(-(t+this._maxZ)*this._subdivisionsY/this._height+this._subdivisionsY),r=this._heightQuads[n*this._subdivisionsX+i];let s;return s=t<r.slope.x*e+r.slope.y?r.facet1:r.facet2,s}_initHeightQuads(){const e=this._subdivisionsX,t=this._subdivisionsY;this._heightQuads=new Array;for(let i=0;i<t;i++)for(let t=0;t<e;t++){const n={slope:U.Zero(),facet1:new G(0,0,0,0),facet2:new G(0,0,0,0)};this._heightQuads[i*e+t]=n}return this}_computeHeightQuads(){const e=this.getVerticesData(si.PositionKind);if(!e)return this;const t=H.Vector3[3],i=H.Vector3[2],n=H.Vector3[1],r=H.Vector3[0],s=H.Vector3[4],a=H.Vector3[5],o=H.Vector3[6],l=H.Vector3[7],c=H.Vector3[8];let h=0,d=0,u=0,f=0,_=0,m=0,p=0;const g=this._subdivisionsX,E=this._subdivisionsY;for(let T=0;T<E;T++)for(let E=0;E<g;E++){h=3*E,d=T*(g+1)*3,u=(T+1)*(g+1)*3,t.x=e[d+h],t.y=e[d+h+1],t.z=e[d+h+2],i.x=e[d+h+3],i.y=e[d+h+4],i.z=e[d+h+5],n.x=e[u+h],n.y=e[u+h+1],n.z=e[u+h+2],r.x=e[u+h+3],r.y=e[u+h+4],r.z=e[u+h+5],f=(r.z-t.z)/(r.x-t.x),_=t.z-f*t.x,i.subtractToRef(t,s),n.subtractToRef(t,a),r.subtractToRef(t,o),B.CrossToRef(o,a,l),B.CrossToRef(s,o,c),l.normalize(),c.normalize(),m=-(l.x*t.x+l.y*t.y+l.z*t.z),p=-(c.x*i.x+c.y*i.y+c.z*i.z);const A=this._heightQuads[T*g+E];A.slope.copyFromFloats(f,_),A.facet1.copyFromFloats(l.x,l.y,l.z,m),A.facet2.copyFromFloats(c.x,c.y,c.z,p)}return this}serialize(e){super.serialize(e),e.subdivisionsX=this._subdivisionsX,e.subdivisionsY=this._subdivisionsY,e.minX=this._minX,e.maxX=this._maxX,e.minZ=this._minZ,e.maxZ=this._maxZ,e.width=this._width,e.height=this._height}static Parse(e,t){const i=new $s(e.name,t);return i._subdivisionsX=e.subdivisionsX||1,i._subdivisionsY=e.subdivisionsY||1,i._minX=e.minX,i._maxX=e.maxX,i._minZ=e.minZ,i._maxZ=e.maxZ,i._width=e.width,i._height=e.height,i}}function ea(e){const t=[],i=[],n=[],r=[];let s,a;const o=e.width||1,l=e.height||1,c=0|(e.subdivisionsX||e.subdivisions||1),h=0|(e.subdivisionsY||e.subdivisions||1);for(s=0;s<=h;s++)for(a=0;a<=c;a++){const e=new B(a*o/c-o/2,0,(h-s)*l/h-l/2),t=new B(0,1,0);i.push(e.x,e.y,e.z),n.push(t.x,t.y,t.z),r.push(a/c,1-s/h)}for(s=0;s<h;s++)for(a=0;a<c;a++)t.push(a+1+(s+1)*(c+1)),t.push(a+1+s*(c+1)),t.push(a+s*(c+1)),t.push(a+(s+1)*(c+1)),t.push(a+1+(s+1)*(c+1)),t.push(a+s*(c+1));const d=new Ti;return d.indices=t,d.positions=i,d.normals=n,d.uvs=r,d}function ta(e){const t=void 0!==e.xmin&&null!==e.xmin?e.xmin:-1,i=void 0!==e.zmin&&null!==e.zmin?e.zmin:-1,n=void 0!==e.xmax&&null!==e.xmax?e.xmax:1,r=void 0!==e.zmax&&null!==e.zmax?e.zmax:1,s=e.subdivisions||{w:1,h:1},a=e.precision||{w:1,h:1},o=[],l=[],c=[],h=[];let d,u,f,_;s.h=s.h<1?1:s.h,s.w=s.w<1?1:s.w,a.w=a.w<1?1:a.w,a.h=a.h<1?1:a.h;const m=(n-t)/s.w,p=(r-i)/s.h;function g(e,t,i,n){const r=l.length/3,s=a.w+1;for(d=0;d<a.h;d++)for(u=0;u<a.w;u++){const e=[r+u+d*s,r+(u+1)+d*s,r+(u+1)+(d+1)*s,r+u+(d+1)*s];o.push(e[1]),o.push(e[2]),o.push(e[3]),o.push(e[0]),o.push(e[1]),o.push(e[3])}const f=B.Zero(),_=new B(0,1,0);for(d=0;d<=a.h;d++)for(f.z=d*(n-t)/a.h+t,u=0;u<=a.w;u++)f.x=u*(i-e)/a.w+e,f.y=0,l.push(f.x,f.y,f.z),c.push(_.x,_.y,_.z),h.push(u/a.w,d/a.h)}for(f=0;f<s.h;f++)for(_=0;_<s.w;_++)g(t+_*m,i+f*p,t+(_+1)*m,i+(f+1)*p);const E=new Ti;return E.indices=o,E.positions=l,E.normals=c,E.uvs=h,E}function ia(e){const t=[],i=[],n=[],r=[];let s,a;const o=e.colorFilter||new ee(.3,.59,.11),l=e.alphaFilter||0;let c=!1;if(e.minHeight>e.maxHeight){c=!0;const t=e.maxHeight;e.maxHeight=e.minHeight,e.minHeight=t}for(s=0;s<=e.subdivisions;s++)for(a=0;a<=e.subdivisions;a++){const t=new B(a*e.width/e.subdivisions-e.width/2,0,(e.subdivisions-s)*e.height/e.subdivisions-e.height/2),h=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 d=e.buffer[h]/255,u=e.buffer[h+1]/255,f=e.buffer[h+2]/255;const _=e.buffer[h+3]/255;c&&(d=1-d,u=1-u,f=1-f);const m=d*o.r+u*o.g+f*o.b;t.y=_>=l?e.minHeight+(e.maxHeight-e.minHeight)*m:e.minHeight-A,e.heightBuffer&&(e.heightBuffer[s*(e.subdivisions+1)+a]=t.y),i.push(t.x,t.y,t.z),n.push(0,0,0),r.push(a/e.subdivisions,1-s/e.subdivisions)}for(s=0;s<e.subdivisions;s++)for(a=0;a<e.subdivisions;a++){const n=a+1+(s+1)*(e.subdivisions+1),r=a+1+s*(e.subdivisions+1),o=a+s*(e.subdivisions+1),l=a+(s+1)*(e.subdivisions+1),c=i[3*n+1]>=e.minHeight,h=i[3*r+1]>=e.minHeight,d=i[3*o+1]>=e.minHeight;c&&h&&d&&(t.push(n),t.push(r),t.push(o));i[3*l+1]>=e.minHeight&&c&&d&&(t.push(l),t.push(n),t.push(o))}Ti.ComputeNormals(i,t,n);const h=new Ti;return h.indices=t,h.positions=i,h.normals=n,h.uvs=r,h}function na(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],n=[];let r=[];const s=e.width||e.size||1,a=e.height||e.size||1,o=e.depth||e.size||1,l=e.wrap||!1;let c=void 0===e.topBaseAt?1:e.topBaseAt,h=void 0===e.bottomBaseAt?0:e.bottomBaseAt;c=(c+4)%4,h=(h+4)%4;let d=[2,0,3,1][c],u=[2,0,1,3][h],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 n=[17,18,19,16],r=[22,23,20,21];for(;d>0;)e.unshift(e.pop()),n.unshift(n.pop()),d--;for(;u>0;)i.unshift(i.pop()),r.unshift(r.pop()),u--;e=e.flat(),i=i.flat(),f=f.concat(e).concat(i),t.push(n[0],n[2],n[3],n[0],n[1],n[2]),t.push(r[0],r[2],r[3],r[0],r[1],r[2])}const _=[s/2,a/2,o/2];r=f.reduce(((e,t,i)=>e.concat(t*_[i%3])),[]);const m=0===e.sideOrientation?0:e.sideOrientation||Ti.DEFAULTSIDE,p=e.faceUV||new Array(6),g=e.faceColors,E=[];for(let e=0;e<6;e++)void 0===p[e]&&(p[e]=new G(0,0,1,1)),g&&void 0===g[e]&&(g[e]=new te(1,1,1,1));for(let e=0;e<6;e++)if(n.push(p[e].z,p[e].w),n.push(p[e].x,p[e].w),n.push(p[e].x,p[e].y),n.push(p[e].z,p[e].y),g)for(let t=0;t<4;t++)E.push(g[e].r,g[e].g,g[e].b,g[e].a);Ti._ComputeSides(m,r,t,i,n,e.frontUVs,e.backUVs);const T=new Ti;if(T.indices=t,T.positions=r,T.normals=i,T.uvs=n,g){const e=m===Ti.DOUBLESIDE?E.concat(E):E;T.colors=e}return T}function ra(e,t={},i=null){const n=new ln(e,i);t.sideOrientation=ln._GetDefaultSideOrientation(t.sideOrientation),n._originalBuilderSideOrientation=t.sideOrientation;return na(t).applyToMesh(n,t.updatable),n}Ti.CreateGround=ea,Ti.CreateTiledGround=ta,Ti.CreateGroundFromHeightMap=ia,ln.CreateGround=(e,t,i,n,r,s)=>function(e,t={},i){const n=new $s(e,i);return n._setReady(!1),n._subdivisionsX=t.subdivisionsX||t.subdivisions||1,n._subdivisionsY=t.subdivisionsY||t.subdivisions||1,n._width=t.width||1,n._height=t.height||1,n._maxX=n._width/2,n._maxZ=n._height/2,n._minX=-n._maxX,n._minZ=-n._maxZ,ea(t).applyToMesh(n,t.updatable),n._setReady(!0),n}(e,{width:t,height:i,subdivisions:n,updatable:s},r),ln.CreateTiledGround=(e,t,i,n,r,s,a,o,l)=>function(e,t,i=null){const n=new ln(e,i);return ta(t).applyToMesh(n,t.updatable),n}(e,{xmin:t,zmin:i,xmax:n,zmax:r,subdivisions:s,precision:a,updatable:l},o),ln.CreateGroundFromHeightMap=(e,t,i,n,r,s,a,o,l,c,h)=>function(e,t,i={},n=null){const r=i.width||10,s=i.height||10,a=i.subdivisions||1,o=i.minHeight||0,l=i.maxHeight||1,c=i.colorFilter||new ee(.3,.59,.11),h=i.alphaFilter||0,d=i.updatable,u=i.onReady;n=n||y.LastCreatedScene;const f=new $s(e,n);let _;f._subdivisionsX=a,f._subdivisionsY=a,f._width=r,f._height=s,f._maxX=f._width/2,f._maxZ=f._height/2,f._minX=-f._maxX,f._minZ=-f._maxZ,f._setReady(!1),i.passHeightBufferInCallback&&(_=new Float32Array((a+1)*(a+1)));const m=(e,t,i)=>{ia({width:r,height:s,subdivisions:a,minHeight:o,maxHeight:l,colorFilter:c,buffer:e,bufferWidth:t,bufferHeight:i,alphaFilter:h,heightBuffer:_}).applyToMesh(f,d),u&&u(f,_),f._setReady(!0)};if("string"==typeof t){const e=e=>{const t=e.width,i=e.height;if(n.isDisposed)return;const r=n?.getEngine().resizeImageBitmap(e,t,i);m(r,t,i)};Yt.LoadImage(t,e,i.onError?i.onError:()=>{},n.offlineProvider)}else m(t.data,t.width,t.height);return f}(e,t,{width:i,height:n,subdivisions:r,minHeight:s,maxHeight:a,updatable:l,onReady:c,alphaFilter:h},o),Ti.CreateBox=na,ln.CreateBox=(e,t,i=null,n,r)=>ra(e,{size:t,sideOrientation:r,updatable:n},i);class sa{get resolve(){return this._resolve}get reject(){return this._reject}constructor(){this.promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}}class aa{constructor(){this._currentOperation=Promise.resolve()}lockAsync(e,t){t?.throwIfAborted();const i=t?()=>(t.throwIfAborted(),e()):e,n=this._currentOperation.then(i);return this._currentOperation=new Promise((e=>n.then((()=>e()),e))),n}static async LockAsync(e,t,i){if(i?.throwIfAborted(),0===t.length)return await e();const n=new sa;let r=0;return t.forEach((s=>s.lockAsync((async()=>(r++,r===t.length&&n.resolve(await e()),n.promise)),i).catch((e=>n.reject(e))))),n.promise}}class oa{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===Cn.ANIMATIONTYPE_MATRIX&&(this._animationState.workValue=k.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 r=t.getEvents();r&&r.length>0&&r.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 n=e;for(let e=0;e<i.length-1;e++){const t=i[e];if(n=n[t],void 0===n)throw new Error(`Invalid property (${t}) in property path (${i.join(".")})`)}this._targetPath=i[i.length-1],this._activeTargets[t]=n}else this._targetPath=i[0],this._activeTargets[t]=e;if(void 0===this._activeTargets[t][this._targetPath])throw new Error(`Invalid property (${this._targetPath}) in property path (${i.join(".")})`)}get animation(){return this._animation}reset(e=!1){if(e)if(this._target instanceof Array){let e=0;for(const t of this._target)void 0!==this._originalValue[e]&&this._setValue(t,this._activeTargets[e],this._originalValue[e],-1,e),e++}else void 0!==this._originalValue[0]&&this._setValue(this._target,this._directTarget,this._originalValue[0],-1,0);this._offsetsCache={},this._highLimitsCache={},this._currentFrame=0,this._blendingFactor=0;for(let e=0;e<this._events.length;e++)this._events[e].isDone=!1}isStopped(){return this._stopped}dispose(){const e=this._animation.runtimeAnimations.indexOf(this);e>-1&&this._animation.runtimeAnimations.splice(e,1)}setValue(e,t){if(this._targetIsArray)for(let i=0;i<this._target.length;i++){const n=this._target[i];this._setValue(n,this._activeTargets[i],e,t,i)}else this._setValue(this._target,this._directTarget,e,t,0)}_getOriginalValues(e=0){let t;const i=this._activeTargets[e];t=i.getLocalMatrix&&"_matrix"===this._targetPath?i.getLocalMatrix():i[this._targetPath],t&&t.clone?this._originalValue[e]=t.clone():this._originalValue[e]=t}_setValue(e,t,i,n,r){if(this._currentActiveTarget=t,this._weight=n,this._enableBlending&&this._blendingFactor<=1){if(!this._originalBlendValue){const e=t[this._targetPath];e.clone?this._originalBlendValue=e.clone():this._originalBlendValue=e}this._originalBlendValue.m?Cn.AllowMatrixDecomposeForInterpolation?this._currentValue?k.DecomposeLerpToRef(this._originalBlendValue,i,this._blendingFactor,this._currentValue):this._currentValue=k.DecomposeLerp(this._originalBlendValue,i,this._blendingFactor):this._currentValue?k.LerpToRef(this._originalBlendValue,i,this._blendingFactor,this._currentValue):this._currentValue=k.Lerp(this._originalBlendValue,i,this._blendingFactor):this._currentValue=Cn._UniversalLerp(this._originalBlendValue,i,this._blendingFactor);const n=e&&e.animationPropertiesOverride?e.animationPropertiesOverride.blendingSpeed:this._animation.blendingSpeed;this._blendingFactor+=n}else this._currentValue?this._currentValue.copyFrom?this._currentValue.copyFrom(i):this._currentValue=i:this._currentValue=i?.clone?i.clone():i;-1!==n?this._scene._registerTargetForLateAnimationBinding(this,this._originalValue[r]):this._animationState.loopMode===Cn.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT?this._currentValue.addToRef?this._currentValue.addToRef(this._originalValue[r],t[this._targetPath]):t[this._targetPath]=this._originalValue[r]+this._currentValue:t[this._targetPath]=this._currentValue,e.markAsDirty&&e.markAsDirty(this._animation.targetProperty)}_getCorrectLoopMode(){return this._target&&this._target.animationPropertiesOverride?this._target.animationPropertiesOverride.loopMode:this._animation.loopMode}goToFrame(e,t=-1){const i=this._animation.getKeys();e<i[0].frame?e=i[0].frame:e>i[i.length-1].frame&&(e=i[i.length-1].frame);const n=this._events;if(n.length)for(let t=0;t<n.length;t++)n[t].onlyOnce||(n[t].isDone=n[t].frame<e);this._currentFrame=e;const r=this._animation._interpolate(e,this._animationState);this.setValue(r,t)}_prepareForSpeedRatioChange(e){const t=this._previousElapsedTime*(this._animation.framePerSecond*e)/1e3;this._absoluteFrameOffset=this._previousAbsoluteFrame-t}animate(e,t,i,n,r,s=-1){const a=this._animation,o=a.targetPropertyPath;if(!o||o.length<1)return this._stopped=!0,!1;let l=!0;(t<this._minFrame||t>this._maxFrame)&&(t=this._minFrame),(i<this._minFrame||i>this._maxFrame)&&(i=this._maxFrame);const c=i-t;let h,d=e*(a.framePerSecond*r)/1e3+this._absoluteFrameOffset,u=0,f=!1;const _=n&&this._animationState.loopMode===Cn.ANIMATIONLOOPMODE_YOYO;if(_){const e=(d-t)/c,i=Math.sin(e*Math.PI);d=Math.abs(i)*c+t;const n=i>=0?1:-1;this._yoyoDirection!==n&&(f=!0),this._yoyoDirection=n}if(this._previousElapsedTime=e,this._previousAbsoluteFrame=d,!n&&i>=t&&(d>=c&&r>0||d<=0&&r<0))l=!1,u=a._getKeyValue(this._maxValue);else if(!n&&t>=i&&(d<=c&&r<0||d>=0&&r>0))l=!1,u=a._getKeyValue(this._minValue);else if(this._animationState.loopMode!==Cn.ANIMATIONLOOPMODE_CYCLE){const e=i.toString()+t.toString();if(!this._offsetsCache[e]){this._animationState.repeatCount=0,this._animationState.loopMode=Cn.ANIMATIONLOOPMODE_CYCLE;const n=a._interpolate(t,this._animationState),r=a._interpolate(i,this._animationState);switch(this._animationState.loopMode=this._getCorrectLoopMode(),a.dataType){case Cn.ANIMATIONTYPE_FLOAT:this._offsetsCache[e]=r-n;break;case Cn.ANIMATIONTYPE_QUATERNION:case Cn.ANIMATIONTYPE_VECTOR3:case Cn.ANIMATIONTYPE_VECTOR2:case Cn.ANIMATIONTYPE_SIZE:case Cn.ANIMATIONTYPE_COLOR3:this._offsetsCache[e]=r.subtract(n)}this._highLimitsCache[e]=r}u=this._highLimitsCache[e],h=this._offsetsCache[e]}if(void 0===h)switch(a.dataType){case Cn.ANIMATIONTYPE_FLOAT:h=0;break;case Cn.ANIMATIONTYPE_QUATERNION:h=En;break;case Cn.ANIMATIONTYPE_VECTOR3:h=Tn;break;case Cn.ANIMATIONTYPE_VECTOR2:h=An;break;case Cn.ANIMATIONTYPE_SIZE:h=vn;break;case Cn.ANIMATIONTYPE_COLOR3:h=Rn;break;case Cn.ANIMATIONTYPE_COLOR4:h=Sn}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&&t<i?l&&0!==c?i+d%c:t:l&&0!==c?t+d%c:i;const p=this._events;if(!_&&(r>0&&this.currentFrame>m||r<0&&this.currentFrame<m)||_&&f){this._onLoop();for(let e=0;e<p.length;e++)p[e].onlyOnce||(p[e].isDone=!1);this._animationState.key=r>0?0:a.getKeys().length-1}this._currentFrame=m,this._animationState.repeatCount=0===c?0:d/c|0,this._animationState.highLimitValue=u,this._animationState.offsetValue=h;const g=a._interpolate(m,this._animationState);if(this.setValue(g,s),p.length)for(let e=0;e<p.length;e++)if(c>=0&&m>=p[e].frame&&p[e].frame>=t||c<0&&m<=p[e].frame&&p[e].frame<=t){const t=p[e];t.isDone||(t.onlyOnce&&(p.splice(e,1),e--),t.isDone=!0,t.action(m))}return l||(this._stopped=!0),l}}class la extends ae{get _matrix(){return this._compose(),this._localMatrix}set _matrix(e){(e.updateFlag!==this._localMatrix.updateFlag||this._needToCompose)&&(this._needToCompose=!1,this._localMatrix.copyFrom(e),this._markAsDirtyAndDecompose())}constructor(e,t,i=null,n=null,r=null,s=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=n?.clone()??k.Identity(),this._restMatrix=r??this._localMatrix.clone(),this._bindMatrix=s??this._localMatrix.clone(),this._index=a,this._absoluteMatrix=new k,this._absoluteBindMatrix=new k,this._absoluteInverseBindMatrix=new k,this._finalMatrix=new k,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=H.Vector3[0],t=H.Quaternion[0],i=H.Vector3[1];this.getRestMatrix().decompose(e,t,i),this._linkedTransformNode.position.copyFrom(i),this._linkedTransformNode.rotationQuaternion=this._linkedTransformNode.rotationQuaternion??V.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=B.Zero(),this._localRotation=V.Zero(),this._localPosition=B.Zero()),this._localMatrix.decompose(this._localScaling,this._localRotation,this._localPosition))}_compose(){this._needToCompose&&(this._localScaling?(this._needToCompose=!1,k.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<this.children.length;e++)this.children[e]._updateAbsoluteBindMatrices();this._scalingDeterminant=this._absoluteBindMatrix.determinant()<0?-1:1}markAsDirty(){return this._currentRenderId++,this._childUpdateId++,this._skeleton._markAsDirty(),this}_markAsDirtyAndCompose(){this.markAsDirty(),this._needToCompose=!0}_markAsDirtyAndDecompose(){this.markAsDirty(),this._needToDecompose=!0}_updatePosition(e,t=0,i,n=!0){const r=this.getLocalMatrix();if(0==t)n?(r.addAtIndex(12,e.x),r.addAtIndex(13,e.y),r.addAtIndex(14,e.z)):r.setTranslationFromFloats(e.x,e.y,e.z);else{let t=null;i&&(t=i.getWorldMatrix()),this._skeleton.computeAbsoluteMatrices();const s=la._TmpMats[0],a=la._TmpVecs[0];this.parent?i&&t?(s.copyFrom(this.parent.getAbsoluteMatrix()),s.multiplyToRef(t,s)):s.copyFrom(this.parent.getAbsoluteMatrix()):k.IdentityToRef(s),n&&s.setTranslationFromFloats(0,0,0),s.invert(),B.TransformCoordinatesToRef(e,s,a),n?(r.addAtIndex(12,a.x),r.addAtIndex(13,a.y),r.addAtIndex(14,a.z)):r.setTranslationFromFloats(a.x,a.y,a.z)}this._markAsDirtyAndDecompose()}translate(e,t=0,i){this._updatePosition(e,t,i,!0)}setPosition(e,t=0,i){this._updatePosition(e,t,i,!1)}setAbsolutePosition(e,t){this.setPosition(e,1,t)}scale(e,t,i,n=!1){const r=this.getLocalMatrix(),s=la._TmpMats[0];k.ScalingToRef(e,t,i,s),s.multiplyToRef(r,r),s.invert();for(const n of this.children){const r=n.getLocalMatrix();r.multiplyToRef(s,r),r.multiplyAtIndex(12,e),r.multiplyAtIndex(13,t),r.multiplyAtIndex(14,i),n._markAsDirtyAndDecompose()}if(this._markAsDirtyAndDecompose(),n)for(const r of this.children)r.scale(e,t,i,n)}setScale(e){this._decompose(),this._localScaling.copyFrom(e),this._markAsDirtyAndCompose()}getScale(){return this._decompose(),this._localScaling}getScaleToRef(e){this._decompose(),e.copyFrom(this._localScaling)}setYawPitchRoll(e,t,i,n=0,r){if(0===n){const s=la._TmpQuat;return V.RotationYawPitchRollToRef(e,t,i,s),void this.setRotationQuaternion(s,n,r)}const s=la._TmpMats[0];if(!this._getAbsoluteInverseMatrixUnscaledToRef(s,r))return;const a=la._TmpMats[1];k.RotationYawPitchRollToRef(e,t,i,a),s.multiplyToRef(a,a),this._rotateWithMatrix(a,n,r)}rotate(e,t,i=0,n){const r=la._TmpMats[0];r.setTranslationFromFloats(0,0,0),k.RotationAxisToRef(e,t,r),this._rotateWithMatrix(r,i,n)}setAxisAngle(e,t,i=0,n){if(0===i){const r=la._TmpQuat;return V.RotationAxisToRef(e,t,r),void this.setRotationQuaternion(r,i,n)}const r=la._TmpMats[0];if(!this._getAbsoluteInverseMatrixUnscaledToRef(r,n))return;const s=la._TmpMats[1];k.RotationAxisToRef(e,t,s),r.multiplyToRef(s,s),this._rotateWithMatrix(s,i,n)}setRotation(e,t=0,i){this.setYawPitchRoll(e.y,e.x,e.z,t,i)}setRotationQuaternion(e,t=0,i){if(0===t)return this._decompose(),this._localRotation.copyFrom(e),void this._markAsDirtyAndCompose();const n=la._TmpMats[0];if(!this._getAbsoluteInverseMatrixUnscaledToRef(n,i))return;const r=la._TmpMats[1];k.FromQuaternionToRef(e,r),n.multiplyToRef(r,r),this._rotateWithMatrix(r,t,i)}setRotationMatrix(e,t=0,i){if(0===t){const n=la._TmpQuat;return V.FromRotationMatrixToRef(e,n),void this.setRotationQuaternion(n,t,i)}const n=la._TmpMats[0];if(!this._getAbsoluteInverseMatrixUnscaledToRef(n,i))return;const r=la._TmpMats[1];r.copyFrom(e),n.multiplyToRef(e,r),this._rotateWithMatrix(r,t,i)}_rotateWithMatrix(e,t=0,i){const n=this.getLocalMatrix(),r=n.m[12],s=n.m[13],a=n.m[14],o=this.getParent(),l=la._TmpMats[3],c=la._TmpMats[4];o&&1==t?(i?(l.copyFrom(i.getWorldMatrix()),o.getAbsoluteMatrix().multiplyToRef(l,l)):l.copyFrom(o.getAbsoluteMatrix()),c.copyFrom(l),c.invert(),n.multiplyToRef(l,n),n.multiplyToRef(e,n),n.multiplyToRef(c,n)):1==t&&i?(l.copyFrom(i.getWorldMatrix()),c.copyFrom(l),c.invert(),n.multiplyToRef(l,n),n.multiplyToRef(e,n),n.multiplyToRef(c,n)):n.multiplyToRef(e,n),n.setTranslationFromFloats(r,s,a),this.computeAbsoluteMatrices(),this._markAsDirtyAndDecompose()}_getAbsoluteInverseMatrixUnscaledToRef(e,t){const i=la._TmpMats[2];return e.copyFrom(this.getAbsoluteMatrix()),t?(e.multiplyToRef(t.getWorldMatrix(),e),k.ScalingToRef(t.scaling.x,t.scaling.y,t.scaling.z,i)):k.IdentityToRef(i),e.invert(),!isNaN(e.m[0])&&(i.multiplyAtIndex(0,this._scalingDeterminant),e.multiplyToRef(i,e),!0)}getPosition(e=0,t=null){const i=B.Zero();return this.getPositionToRef(e,t,i),i}getPositionToRef(e=0,t,i){if(0==e){const e=this.getLocalMatrix();i.x=e.m[12],i.y=e.m[13],i.z=e.m[14]}else{let e=null;t&&(e=t.getWorldMatrix()),this._skeleton.computeAbsoluteMatrices();let n=la._TmpMats[0];t&&e?(n.copyFrom(this.getAbsoluteMatrix()),n.multiplyToRef(e,n)):n=this.getAbsoluteMatrix(),i.x=n.m[12],i.y=n.m[13],i.z=n.m[14]}}getAbsolutePosition(e=null){const t=B.Zero();return this.getPositionToRef(1,e,t),t}getAbsolutePositionToRef(e,t){this.getPositionToRef(1,e,t)}computeAbsoluteMatrices(){if(this._compose(),this.parent)this._localMatrix.multiplyToRef(this.parent._absoluteMatrix,this._absoluteMatrix);else{this._absoluteMatrix.copyFrom(this._localMatrix);const e=this._skeleton.getPoseMatrix();e&&this._absoluteMatrix.multiplyToRef(e,this._absoluteMatrix)}const e=this.children,t=e.length;for(let i=0;i<t;i++)e[i].computeAbsoluteMatrices()}computeAbsoluteTransforms(){this.computeAbsoluteMatrices()}getDirection(e,t=null){const i=B.Zero();return this.getDirectionToRef(e,t,i),i}getDirectionToRef(e,t=null,i){let n=null;t&&(n=t.getWorldMatrix()),this._skeleton.computeAbsoluteMatrices();const r=la._TmpMats[0];r.copyFrom(this.getAbsoluteMatrix()),t&&n&&r.multiplyToRef(n,r),B.TransformNormalToRef(e,r,i),i.normalize()}getRotation(e=0,t=null){const i=B.Zero();return this.getRotationToRef(e,t,i),i}getRotationToRef(e=0,t=null,i){const n=la._TmpQuat;this.getRotationQuaternionToRef(e,t,n),n.toEulerAnglesToRef(i)}getRotationQuaternion(e=0,t=null){const i=V.Identity();return this.getRotationQuaternionToRef(e,t,i),i}getRotationQuaternionToRef(e=0,t=null,i){if(0==e)this._decompose(),i.copyFrom(this._localRotation);else{const e=la._TmpMats[0],n=this.getAbsoluteMatrix();t?n.multiplyToRef(t.getWorldMatrix(),e):e.copyFrom(n),e.multiplyAtIndex(0,this._scalingDeterminant),e.multiplyAtIndex(1,this._scalingDeterminant),e.multiplyAtIndex(2,this._scalingDeterminant),e.decompose(void 0,i,void 0)}}getRotationMatrix(e=0,t){const i=k.Identity();return this.getRotationMatrixToRef(e,t,i),i}getRotationMatrixToRef(e=0,t,i){if(0==e)this.getLocalMatrix().getRotationMatrixToRef(i);else{const e=la._TmpMats[0],n=this.getAbsoluteMatrix();t?n.multiplyToRef(t.getWorldMatrix(),e):e.copyFrom(n),e.multiplyAtIndex(0,this._scalingDeterminant),e.multiplyAtIndex(1,this._scalingDeterminant),e.multiplyAtIndex(2,this._scalingDeterminant),e.getRotationMatrixToRef(i)}}getAbsolutePositionFromLocal(e,t=null){const i=B.Zero();return this.getAbsolutePositionFromLocalToRef(e,t,i),i}getAbsolutePositionFromLocalToRef(e,t=null,i){let n=null;t&&(n=t.getWorldMatrix()),this._skeleton.computeAbsoluteMatrices();const r=la._TmpMats[0];r.copyFrom(this.getAbsoluteMatrix()),t&&n&&r.multiplyToRef(n,r),B.TransformCoordinatesToRef(e,r,i)}getLocalPositionFromAbsolute(e,t=null){const i=B.Zero();return this.getLocalPositionFromAbsoluteToRef(e,t,i),i}getLocalPositionFromAbsoluteToRef(e,t=null,i){let n=null;t&&(n=t.getWorldMatrix()),this._skeleton.computeAbsoluteMatrices();const r=la._TmpMats[0];r.copyFrom(this.getAbsoluteMatrix()),t&&n&&r.multiplyToRef(n,r),r.invert(),B.TransformCoordinatesToRef(e,r,i)}setCurrentPoseAsRest(){this.setRestMatrix(this.getLocalMatrix())}}la._TmpVecs=v(2,B.Zero),la._TmpQuat=V.Identity(),la._TmpMats=v(5,k.Identity);class ca{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<this._runtimeAnimations.length;t++){this._runtimeAnimations[t]._prepareForSpeedRatioChange(e)}this._speedRatio=e,null!==this._goToFrame&&this.goToFrame(this._goToFrame)}get elapsedTime(){return null===this._localDelayOffset?0:this._scene._animationTime-this._localDelayOffset}constructor(e,t,i=0,n=100,r=!1,s=1,a,o,l,c=!1,h=0){this.target=t,this.fromFrame=i,this.toFrame=n,this.loopAnimation=r,this.onAnimationEnd=a,this.onAnimationLoop=l,this.isAdditive=c,this.playOrder=h,this._localDelayOffset=null,this._pausedDelay=null,this._manualJumpDelay=null,this._runtimeAnimations=new Array,this._paused=!1,this._speedRatio=1,this._weight=-1,this._syncRoot=null,this._frameToSyncFromJump=null,this._goToFrame=null,this.disposeOnEnd=!0,this.animationStarted=!1,this.onAnimationEndObservable=new g,this.onAnimationLoopObservable=new g,this._scene=e,o&&this.appendAnimations(t,o),this._speedRatio=s,e._activeAnimatables.push(this)}syncWith(e){if(this._syncRoot=e,e){const e=this._scene._activeAnimatables.indexOf(this);e>-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<t.length;i++){const n=t[i],r=new oa(e,n,this._scene,this);r._onLoop=()=>{this.onAnimationLoopObservable.notifyObservers(this),this.onAnimationLoop&&this.onAnimationLoop()},this._runtimeAnimations.push(r)}}getAnimationByTargetProperty(e){const t=this._runtimeAnimations;for(let i=0;i<t.length;i++)if(t[i].animation.targetProperty===e)return t[i].animation;return null}getRuntimeAnimationByTargetProperty(e){const t=this._runtimeAnimations;for(let i=0;i<t.length;i++)if(t[i].animation.targetProperty===e)return t[i];return null}reset(){const e=this._runtimeAnimations;for(let t=0;t<e.length;t++)e[t].reset(!0);this._localDelayOffset=null,this._pausedDelay=null}enableBlending(e){const t=this._runtimeAnimations;for(let i=0;i<t.length;i++)t[i].animation.enableBlending=!0,t[i].animation.blendingSpeed=e}disableBlending(){const e=this._runtimeAnimations;for(let t=0;t<e.length;t++)e[t].animation.enableBlending=!1}goToFrame(e){const t=this._runtimeAnimations;if(t[0]){const i=t[0].animation.framePerSecond;this._frameToSyncFromJump=this._frameToSyncFromJump??t[0].currentFrame;const n=0===this.speedRatio?0:(e-this._frameToSyncFromJump)/i*1e3/this.speedRatio;this._manualJumpDelay=-n}for(let i=0;i<t.length;i++)t[i].goToFrame(e,this._weight);this._goToFrame=e}get paused(){return this._paused}pause(){this._paused||(this._paused=!0)}restart(){this._paused=!1}_raiseOnAnimationEnd(){this.onAnimationEnd&&this.onAnimationEnd(),this.onAnimationEndObservable.notifyObservers(this)}stop(e,t,i=!1,n=!1){if(e||t){const r=this._scene._activeAnimatables.indexOf(this);if(r>-1){const s=this._runtimeAnimations;for(let i=s.length-1;i>=0;i--){const n=s[i];e&&n.animation.name!=e||(t&&!t(n.target)||(n.dispose(),s.splice(i,1)))}0==s.length&&(i||this._scene._activeAnimatables.splice(r,1),n||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<t.length;e++)t[e].dispose();this._runtimeAnimations.length=0,n||this._raiseOnAnimationEnd()}}}waitAsync(){return new Promise((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 n;for(n=0;n<i.length;n++){const r=i[n].animate(e-this._localDelayOffset,this.fromFrame,this.toFrame,this.loopAnimation,this._speedRatio,this._weight);t=t||r}if(this.animationStarted=t,!t){if(this.disposeOnEnd)for(n=this._scene._activeAnimatables.indexOf(this),this._scene._activeAnimatables.splice(n,1),n=0;n<i.length;n++)i[n].dispose();this._raiseOnAnimationEnd(),this.disposeOnEnd&&(this.onAnimationEnd=null,this.onAnimationLoop=null,this.onAnimationLoopObservable.clear(),this.onAnimationEndObservable.clear())}return t}}Rr.prototype._animate=function(e){if(!this.animationsEnabled)return;const t=_e.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 n=this._animationTime;for(let e=0;e<i.length;e++){const t=i[e];!t._animate(n)&&t.disposeOnEnd&&e--}this._processLateAnimationBindings()},Rr.prototype.sortActiveAnimatables=function(){this._activeAnimatables.sort(((e,t)=>e.playOrder-t.playOrder))},Rr.prototype.beginWeightedAnimation=function(e,t,i,n=1,r,s=1,a,o,l,c,h=!1){const d=this.beginAnimation(e,t,i,r,s,a,o,!1,l,c,h);return d.weight=n,d},Rr.prototype.beginAnimation=function(e,t,i,n,r=1,s,a,o=!0,l,c,h=!1){t>i&&r>0&&(r*=-1),o&&this.stopAnimation(e,void 0,l),a||(a=new ca(this,e,t,i,n,r,s,void 0,c,h));const d=!l||l(e);if(e.animations&&d&&a.appendAnimations(e,e.animations),e.getAnimatables){const h=e.getAnimatables();for(let e=0;e<h.length;e++)this.beginAnimation(h[e],t,i,n,r,s,a,o,l,c)}return a.reset(),a},Rr.prototype.beginHierarchyAnimation=function(e,t,i,n,r,s=1,a,o,l=!0,c,h,d=!1){const u=e.getDescendants(t),f=[];f.push(this.beginAnimation(e,i,n,r,s,a,o,l,c,void 0,d));for(const e of u)f.push(this.beginAnimation(e,i,n,r,s,a,o,l,c,void 0,d));return f},Rr.prototype.beginDirectAnimation=function(e,t,i,n,r,s,a,o,l=!1){if(void 0===s&&(s=1),i>n&&s>0)s*=-1;else if(n>i&&s<0){const e=n;n=i,i=e}return new ca(this,e,i,n,r,s,a,t,o,l)},Rr.prototype.beginDirectHierarchyAnimation=function(e,t,i,n,r,s,a,o,l,c=!1){const h=e.getDescendants(t),d=[];d.push(this.beginDirectAnimation(e,i,n,r,s,a,o,l,c));for(const e of h)d.push(this.beginDirectAnimation(e,i,n,r,s,a,o,l,c));return d},Rr.prototype.getAnimatableByTarget=function(e){for(let t=0;t<this._activeAnimatables.length;t++)if(this._activeAnimatables[t].target===e)return this._activeAnimatables[t];return null},Rr.prototype.getAllAnimatablesByTarget=function(e){const t=[];for(let i=0;i<this._activeAnimatables.length;i++)this._activeAnimatables[i].target===e&&t.push(this._activeAnimatables[i]);return t},Rr.prototype.stopAnimation=function(e,t,i){const n=this.getAllAnimatablesByTarget(e);for(const e of n)e.stop(t,i)},Rr.prototype.stopAllAnimations=function(){if(this._activeAnimatables){for(let e=0;e<this._activeAnimatables.length;e++)this._activeAnimatables[e].stop(void 0,void 0,!0);this._activeAnimatables.length=0}for(const e of this.animationGroups)e.stop()},Rr.prototype._registerTargetForLateAnimationBinding=function(e,t){const i=e.target;this._registeredForLateAnimationBindings.pushNoDuplicate(i),i._lateAnimationHolders||(i._lateAnimationHolders={}),i._lateAnimationHolders[e.targetPath]||(i._lateAnimationHolders[e.targetPath]={totalWeight:0,totalAdditiveWeight:0,animations:[],additiveAnimations:[],originalValue:t}),e.isAdditive?(i._lateAnimationHolders[e.targetPath].additiveAnimations.push(e),i._lateAnimationHolders[e.targetPath].totalAdditiveWeight+=e.weight):(i._lateAnimationHolders[e.targetPath].animations.push(e),i._lateAnimationHolders[e.targetPath].totalWeight+=e.weight)},Rr.prototype._processLateAnimationBindingsForMatrices=function(e){if(0===e.totalWeight&&0===e.totalAdditiveWeight)return e.originalValue;let t=1;const i=H.Vector3[0],n=H.Vector3[1],r=H.Quaternion[0];let s=0;const a=e.animations[0],o=e.originalValue;let l=1,c=!1;if(e.totalWeight<1)l=1-e.totalWeight,o.decompose(n,r,i);else{if(s=1,t=e.totalWeight,l=a.weight/t,1==l){if(!e.totalAdditiveWeight)return a.currentValue;c=!0}a.currentValue.decompose(n,r,i)}if(!c){n.scaleInPlace(l),i.scaleInPlace(l),r.scaleInPlace(l);for(let a=s;a<e.animations.length;a++){const s=e.animations[a];if(0===s.weight)continue;l=s.weight/t;const o=H.Vector3[2],c=H.Vector3[3],h=H.Quaternion[1];s.currentValue.decompose(c,h,o),c.scaleAndAddToRef(l,n),h.scaleAndAddToRef(V.Dot(r,h)>0?l:-l,r),o.scaleAndAddToRef(l,i)}r.normalize()}for(let t=0;t<e.additiveAnimations.length;t++){const s=e.additiveAnimations[t];if(0===s.weight)continue;const a=H.Vector3[2],o=H.Vector3[3],l=H.Quaternion[1];s.currentValue.decompose(o,l,a),o.multiplyToRef(n,o),B.LerpToRef(n,o,s.weight,n),r.multiplyToRef(l,l),V.SlerpToRef(r,l,s.weight,r),a.scaleAndAddToRef(s.weight,i)}const h=a?a._animationState.workValue:H.Matrix[0].clone();return k.ComposeToRef(n,r,i,h),h},Rr.prototype._processLateAnimationBindingsForQuaternions=function(e,t){if(0===e.totalWeight&&0===e.totalAdditiveWeight)return t;const i=e.animations[0],n=e.originalValue;let r=t;if(0===e.totalWeight&&e.totalAdditiveWeight>0)r.copyFrom(n);else if(1===e.animations.length){if(V.SlerpToRef(n,i.currentValue,Math.min(1,e.totalWeight),r),0===e.totalAdditiveWeight)return r}else if(e.animations.length>1){let i,s,a=1;if(e.totalWeight<1){const t=1-e.totalWeight;i=[],s=[],i.push(n),s.push(t)}else{if(2===e.animations.length&&(V.SlerpToRef(e.animations[0].currentValue,e.animations[1].currentValue,e.animations[1].weight/e.totalWeight,t),0===e.totalAdditiveWeight))return t;i=[],s=[],a=e.totalWeight}for(let t=0;t<e.animations.length;t++){const n=e.animations[t];i.push(n.currentValue),s.push(n.weight/a)}let o=0;for(let e=0;e<i.length;)e?(o+=s[e],V.SlerpToRef(r,i[e],s[e]/o,r),e++):(V.SlerpToRef(i[e],i[e+1],s[e+1]/(s[e]+s[e+1]),t),r=t,o=s[e]+s[e+1],e+=2)}for(let t=0;t<e.additiveAnimations.length;t++){const i=e.additiveAnimations[t];0!==i.weight&&(r.multiplyToRef(i.currentValue,H.Quaternion[0]),V.SlerpToRef(r,H.Quaternion[0],i.weight,r))}return r},Rr.prototype._processLateAnimationBindings=function(){if(this._registeredForLateAnimationBindings.length){for(let e=0;e<this._registeredForLateAnimationBindings.length;e++){const t=this._registeredForLateAnimationBindings.data[e];for(const e in t._lateAnimationHolders){const i=t._lateAnimationHolders[e],n=i.animations[0],r=i.originalValue;if(null==r)continue;const s=Cn.AllowMatrixDecomposeForInterpolation&&r.m;let a=t[e];if(s)a=this._processLateAnimationBindingsForMatrices(i);else{if(void 0!==r.w)a=this._processLateAnimationBindingsForQuaternions(i,a||V.Identity());else{let e=0,t=1;const s=n&&n._animationState.loopMode===Cn.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT;if(i.totalWeight<1)a=s?r.clone?r.clone():r:n&&r.scale?r.scale(1-i.totalWeight):n?r*(1-i.totalWeight):r.clone?r.clone():r;else if(n){t=i.totalWeight;const o=n.weight/t;a=1!==o?n.currentValue.scale?n.currentValue.scale(o):n.currentValue*o:n.currentValue,s&&(a.addToRef?a.addToRef(r,a):a+=r),e=1}for(let n=e;n<i.animations.length;n++){const e=i.animations[n],r=e.weight/t;r&&(e.currentValue.scaleAndAddToRef?e.currentValue.scaleAndAddToRef(r,a):a+=e.currentValue*r)}for(let e=0;e<i.additiveAnimations.length;e++){const t=i.additiveAnimations[e],n=t.weight;n&&(t.currentValue.scaleAndAddToRef?t.currentValue.scaleAndAddToRef(n,a):a+=t.currentValue*n)}}}t[e]=a}t._lateAnimationHolders={}}this._registeredForLateAnimationBindings.reset()}},la.prototype.copyAnimationRange=function(e,t,i,n=!1,r=null){0===this.animations.length&&(this.animations.push(new Cn(this.name,"_matrix",e.animations[0].framePerSecond,Cn.ANIMATIONTYPE_MATRIX,0)),this.animations[0].setKeys([]));const s=e.animations[0].getRange(t);if(!s)return!1;const a=s.from,o=s.to,l=e.animations[0].getKeys(),c=e.length,h=e.getParent(),d=this.getParent(),u=n&&h&&c&&this.length&&c!==this.length,f=u&&d&&h?d.length/h.length:1,_=n&&!d&&r&&(1!==r.x||1!==r.y||1!==r.z),m=this.animations[0].getKeys();let p,g,E;for(let e=0,t=l.length;e<t;e++)p=l[e],p.frame>=a&&p.frame<=o&&(n?(E=p.value.clone(),u?(g=E.getTranslation(),E.setTranslation(g.scaleInPlace(f))):_&&r?(g=E.getTranslation(),E.setTranslation(g.multiplyInPlace(r))):E=p.value):E=p.value,m.push({frame:p.frame+i,value:E}));return this.animations[0].createRange(t,a+i,o+i),!0};const ha="image/png",da=2,ua=[134,22,135,150,246,214,150,54];function fa(e){if(e.version>da)throw new Error(`Unsupported babylon environment map version "${e.version}". Latest supported version is "${da}".`);return 2===e.version?e:e={...e,version:2,imageType:ha}}function _a(e,t,i){const n=(i=fa(i)).specular;if(!n)return Promise.resolve();e._lodGenerationScale=n.lodGenerationScale;const r=function(e,t){const i=(t=fa(t)).specular;let n=j.Log2(t.width);if(n=Math.round(n)+1,i.mipmaps.length!==6*n)throw new Error(`Unsupported specular mipmaps number "${i.mipmaps.length}"`);const r=new Array(n);for(let t=0;t<n;t++){r[t]=new Array(6);for(let n=0;n<6;n++){const s=i.mipmaps[6*t+n];r[t][n]=new Uint8Array(e.buffer,e.byteOffset+i.specularDataPosition+s.position,s.length)}}return r}(t,i);return pa(e,r,i.imageType)}function ma(e,t,i,n,r,s,a,o,l,c,h){return new Promise(((d,u)=>{if(i){const i=t.createTexture(null,!0,!0,null,Ze.TEXTURE_NEAREST_SAMPLINGMODE,null,(e=>{u(e)}),e);n?.onEffectCreatedObservable.addOnce((o=>{o.executeWhenCompiled((()=>{n.externalTextureSamplerBinding=!0,n.onApply=n=>{n._bindTexture("textureSampler",i),n.setFloat2("scale",1,t._features.needsInvertingBitmap&&e instanceof ImageBitmap?-1:1)},t.scenes.length&&(t.scenes[0].postProcessManager.directRender([n],c,!0,s,a),t.restoreDefaultFramebuffer(),i.dispose(),URL.revokeObjectURL(r),d())}))}))}else{if(t._uploadImageToTexture(h,e,s,a),o){const i=l[a];i&&t._uploadImageToTexture(i._texture,e,s,0)}d()}}))}async function pa(e,t,i=ha){if(!Yt.IsExponentOfTwo(e.width))throw new Error("Texture size must be a power of two");const n=j.ILog2(e.width)+1,r=e.getEngine();let s=!1,a=!1,o=null,l=null,c=null;const h=r.getCaps();e.format=Ze.TEXTUREFORMAT_RGBA,e.type=Ze.TEXTURETYPE_UNSIGNED_INT,e.generateMipMaps=!0,e._cachedAnisotropicFilteringLevel=null,r.updateTextureSamplingMode(Ze.TEXTURE_TRILINEAR_SAMPLINGMODE,e),h.textureLOD?r._features.supportRenderAndCopyToLodForFloatTextures?h.textureHalfFloatRender&&h.textureHalfFloatLinearFiltering?(s=!0,e.type=Ze.TEXTURETYPE_HALF_FLOAT):h.textureFloatRender&&h.textureFloatLinearFiltering&&(s=!0,e.type=Ze.TEXTURETYPE_FLOAT):s=!1:(s=!1,a=!0,c={});let d=0;if(s)r.isWebGPU?(d=1,await Promise.resolve().then((function(){return Eu}))):await Promise.resolve().then((function(){return Mu})),o=new Vr("rgbdDecode","rgbdDecode",null,null,1,null,Ze.TEXTURE_TRILINEAR_SAMPLINGMODE,r,!1,void 0,e.type,void 0,null,!1,void 0,d),e._isRGBD=!1,e.invertY=!1,l=r.createRenderTargetCubeTexture(e.width,{generateDepthBuffer:!1,generateMipMaps:!0,generateStencilBuffer:!1,samplingMode:Ze.TEXTURE_TRILINEAR_SAMPLINGMODE,type:e.type,format:Ze.TEXTUREFORMAT_RGBA});else if(e._isRGBD=!0,e.invertY=!0,a){const t=3,i=e._lodGenerationScale,s=e._lodGenerationOffset;for(let a=0;a<t;a++){const o=(n-1)*i+s,l=s+(o-s)*(1-a/(t-1)),h=Math.round(Math.min(Math.max(l,0),o)),d=new Et(r,2);d.isCube=!0,d.invertY=!0,d.generateMipMaps=!1,r.updateTextureSamplingMode(Ze.TEXTURE_LINEAR_LINEAR,d);const u=new Dr(null);switch(u._isCube=!0,u._texture=d,c[h]=u,a){case 0:e._lodTextureLow=u;break;case 1:e._lodTextureMid=u;break;case 2:e._lodTextureHigh=u}}}const u=[];for(let n=0;n<t.length;n++)for(let h=0;h<6;h++){const d=t[n][h],f=new Blob([d],{type:i}),_=URL.createObjectURL(f);let m;if(r._features.forceBitmapOverHTMLImageElement)m=r.createImageBitmap(f,{premultiplyAlpha:"none"}).then((t=>ma(t,r,s,o,_,h,n,a,c,l,e)));else{const t=new Image;t.src=_,m=new Promise(((i,d)=>{t.onload=()=>{ma(t,r,s,o,_,h,n,a,c,l,e).then((()=>i())).catch((e=>{d(e)}))},t.onerror=e=>{d(e)}}))}u.push(m)}if(t.length<n){let i;const s=Math.pow(2,n-1-t.length),a=s*s*4;switch(e.type){case Ze.TEXTURETYPE_UNSIGNED_INT:i=new Uint8Array(a);break;case Ze.TEXTURETYPE_HALF_FLOAT:i=new Uint16Array(a);break;case Ze.TEXTURETYPE_FLOAT:i=new Float32Array(a)}for(let s=t.length;s<n;s++)for(let t=0;t<6;t++)r._uploadArrayBufferViewToTexture(e,i,t,s)}return Promise.all(u).then((()=>{l&&(r._releaseTexture(e),l._swapAndDie(e)),o&&o.dispose(),a&&(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))}))}var ga,Ea=Object.freeze({__proto__:null,_ENVTextureLoader:class{constructor(){this.supportCascades=!1}loadCubeData(e,t,i,n,r){if(Array.isArray(e))return;const s=function(e){const t=new DataView(e.buffer,e.byteOffset,e.byteLength);let i=0;for(let e=0;e<ua.length;e++)if(t.getUint8(i++)!==ua[e])return de.Error("Not a babylon environment map"),null;let n="",r=0;for(;r=t.getUint8(i++);)n+=String.fromCharCode(r);let s=JSON.parse(n);return s=fa(s),s.specular&&(s.specular.specularDataPosition=i,s.specular.lodGenerationScale=s.specular.lodGenerationScale||.8),s}(e);if(s){t.width=s.width,t.height=s.width;try{!function(e,t){const i=(t=fa(t)).irradiance;if(!i)return;const n=new Is;B.FromArrayToRef(i.x,0,n.x),B.FromArrayToRef(i.y,0,n.y),B.FromArrayToRef(i.z,0,n.z),B.FromArrayToRef(i.xx,0,n.xx),B.FromArrayToRef(i.yy,0,n.yy),B.FromArrayToRef(i.zz,0,n.zz),B.FromArrayToRef(i.yz,0,n.yz),B.FromArrayToRef(i.zx,0,n.zx),B.FromArrayToRef(i.xy,0,n.xy),e._sphericalPolynomial=n}(t,s),_a(t,e,s).then((()=>{t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),n&&n()}),(e=>{r?.("Can not upload environment levels",e)}))}catch(e){r?.("Can not upload environment file",e)}}else r&&r("Can not parse the environment file",null)}loadData(){throw".env not supported in 2d."}}});class Ta{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=Yt.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===Ln.KEYDOWN){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)){-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<this._keys.length;t++){const i=this._keys[t],n=e._computeLocalCameraSpeed();-1!==this.keysLeft.indexOf(i)?e._localDirection.copyFromFloats(-n,0,0):-1!==this.keysUp.indexOf(i)?e._localDirection.copyFromFloats(0,0,n):-1!==this.keysRight.indexOf(i)?e._localDirection.copyFromFloats(n,0,0):-1!==this.keysDown.indexOf(i)?e._localDirection.copyFromFloats(0,0,-n):-1!==this.keysUpward.indexOf(i)?e._localDirection.copyFromFloats(0,n,0):-1!==this.keysDownward.indexOf(i)?e._localDirection.copyFromFloats(0,-n,0):-1!==this.keysRotateLeft.indexOf(i)?(e._localDirection.copyFromFloats(0,0,0),e.cameraRotation.y-=this._getLocalRotation()):-1!==this.keysRotateRight.indexOf(i)?(e._localDirection.copyFromFloats(0,0,0),e.cameraRotation.y+=this._getLocalRotation()):-1!==this.keysRotateUp.indexOf(i)?(e._localDirection.copyFromFloats(0,0,0),e.cameraRotation.x-=this._getLocalRotation()):-1!==this.keysRotateDown.indexOf(i)&&(e._localDirection.copyFromFloats(0,0,0),e.cameraRotation.x+=this._getLocalRotation()),e.getScene().useRightHandedSystem&&(e._localDirection.z*=-1),e.getViewMatrix().invertToRef(e._cameraTransformMatrix),B.TransformNormalToRef(e._localDirection,e._cameraTransformMatrix,e._transformedDirection),e.cameraDirection.addInPlace(e._transformedDirection)}}}getClassName(){return"FreeCameraKeyboardMoveInput"}_onLostFocus(){this._keys.length=0}getSimpleName(){return"keyboard"}_getLocalRotation(){const e=this.camera._calculateHandednessMultiplier();return this.rotationSpeed*this._engine.getDeltaTime()/1e3*e}}e([a()],Ta.prototype,"keysUp",void 0),e([a()],Ta.prototype,"keysUpward",void 0),e([a()],Ta.prototype,"keysDown",void 0),e([a()],Ta.prototype,"keysDownward",void 0),e([a()],Ta.prototype,"keysLeft",void 0),e([a()],Ta.prototype,"keysRight",void 0),e([a()],Ta.prototype,"rotationSpeed",void 0),e([a()],Ta.prototype,"keysRotateLeft",void 0),e([a()],Ta.prototype,"keysRotateRight",void 0),e([a()],Ta.prototype,"keysRotateUp",void 0),e([a()],Ta.prototype,"keysRotateDown",void 0),On.FreeCameraKeyboardMoveInput=Ta;class Aa{constructor(e=!0){this.touchEnabled=e,this.buttons=[0,1,2],this.angularSensibility=2e3,this._previousPosition=null,this.onPointerMovedObservable=new g,this._allowCameraRotation=!0,this._currentActiveButton=-1,this._activePointerId=-1}attachControl(e){e=Yt.BackCompatCameraNoPreventDefault(arguments);const t=this.camera.getEngine(),i=t.getInputElement();this._pointerInput||(this._pointerInput=n=>{const r=n.event,s="touch"===r.pointerType;if(!this.touchEnabled&&s)return;if(n.type!==cn.POINTERMOVE&&-1===this.buttons.indexOf(r.button))return;const a=r.target;if(n.type===cn.POINTERDOWN){if(s&&-1!==this._activePointerId||!s&&-1!==this._currentActiveButton)return;this._activePointerId=r.pointerId;try{a?.setPointerCapture(r.pointerId)}catch(e){}-1===this._currentActiveButton&&(this._currentActiveButton=r.button),this._previousPosition={x:r.clientX,y:r.clientY},e||(r.preventDefault(),i&&i.focus()),t.isPointerLock&&this._onMouseMove&&this._onMouseMove(n.event)}else if(n.type===cn.POINTERUP){if(s&&this._activePointerId!==r.pointerId||!s&&this._currentActiveButton!==r.button)return;try{a?.releasePointerCapture(r.pointerId)}catch(e){}this._currentActiveButton=-1,this._previousPosition=null,e||r.preventDefault(),this._activePointerId=-1}else if(n.type===cn.POINTERMOVE&&(this._activePointerId===r.pointerId||!s))if(t.isPointerLock&&this._onMouseMove)this._onMouseMove(n.event);else if(this._previousPosition){const t=this.camera._calculateHandednessMultiplier(),i=(r.clientX-this._previousPosition.x)*t,n=r.clientY-this._previousPosition.y;this._allowCameraRotation&&(this.camera.cameraRotation.y+=i/this.angularSensibility,this.camera.cameraRotation.x+=n/this.angularSensibility),this.onPointerMovedObservable.notifyObservers({offsetX:i,offsetY:n}),this._previousPosition={x:r.clientX,y:r.clientY},e||r.preventDefault()}}),this._onMouseMove=i=>{if(!t.isPointerLock)return;const n=this.camera._calculateHandednessMultiplier(),r=i.movementX*n;this.camera.cameraRotation.y+=r/this.angularSensibility;const s=i.movementY;this.camera.cameraRotation.x+=s/this.angularSensibility,this._previousPosition=null,e||i.preventDefault()},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,cn.POINTERDOWN|cn.POINTERUP|cn.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"}}e([a()],Aa.prototype,"buttons",void 0),e([a()],Aa.prototype,"angularSensibility",void 0),On.FreeCameraMouseInput=Aa;class va{constructor(){this.wheelPrecisionX=3,this.wheelPrecisionY=3,this.wheelPrecisionZ=3,this.onChangedObservable=new g,this._wheelDeltaX=0,this._wheelDeltaY=0,this._wheelDeltaZ=0,this._ffMultiplier=12,this._normalize=120}attachControl(e){e=Yt.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==cn.POINTERWHEEL)return;const i=t.event,n=i.deltaMode===Bn.DOM_DELTA_LINE?this._ffMultiplier:1;this._wheelDeltaX+=this.wheelPrecisionX*n*i.deltaX/this._normalize,this._wheelDeltaY-=this.wheelPrecisionY*n*i.deltaY/this._normalize,this._wheelDeltaZ+=this.wheelPrecisionZ*n*i.deltaZ/this._normalize,i.preventDefault&&(e||i.preventDefault())},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,cn.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"}}e([a()],va.prototype,"wheelPrecisionX",void 0),e([a()],va.prototype,"wheelPrecisionY",void 0),e([a()],va.prototype,"wheelPrecisionZ",void 0),function(e){e[e.MoveRelative=0]="MoveRelative",e[e.RotateRelative=1]="RotateRelative",e[e.MoveScene=2]="MoveScene"}(ga||(ga={}));class Ra extends va{constructor(){super(...arguments),this._moveRelative=B.Zero(),this._rotateRelative=B.Zero(),this._moveScene=B.Zero(),this._wheelXAction=ga.MoveRelative,this._wheelXActionCoordinate=0,this._wheelYAction=ga.MoveRelative,this._wheelYActionCoordinate=2,this._wheelZAction=null,this._wheelZActionCoordinate=null}getClassName(){return"FreeCameraMouseWheelInput"}set wheelXMoveRelative(e){null===e&&this._wheelXAction!==ga.MoveRelative||(this._wheelXAction=ga.MoveRelative,this._wheelXActionCoordinate=e)}get wheelXMoveRelative(){return this._wheelXAction!==ga.MoveRelative?null:this._wheelXActionCoordinate}set wheelYMoveRelative(e){null===e&&this._wheelYAction!==ga.MoveRelative||(this._wheelYAction=ga.MoveRelative,this._wheelYActionCoordinate=e)}get wheelYMoveRelative(){return this._wheelYAction!==ga.MoveRelative?null:this._wheelYActionCoordinate}set wheelZMoveRelative(e){null===e&&this._wheelZAction!==ga.MoveRelative||(this._wheelZAction=ga.MoveRelative,this._wheelZActionCoordinate=e)}get wheelZMoveRelative(){return this._wheelZAction!==ga.MoveRelative?null:this._wheelZActionCoordinate}set wheelXRotateRelative(e){null===e&&this._wheelXAction!==ga.RotateRelative||(this._wheelXAction=ga.RotateRelative,this._wheelXActionCoordinate=e)}get wheelXRotateRelative(){return this._wheelXAction!==ga.RotateRelative?null:this._wheelXActionCoordinate}set wheelYRotateRelative(e){null===e&&this._wheelYAction!==ga.RotateRelative||(this._wheelYAction=ga.RotateRelative,this._wheelYActionCoordinate=e)}get wheelYRotateRelative(){return this._wheelYAction!==ga.RotateRelative?null:this._wheelYActionCoordinate}set wheelZRotateRelative(e){null===e&&this._wheelZAction!==ga.RotateRelative||(this._wheelZAction=ga.RotateRelative,this._wheelZActionCoordinate=e)}get wheelZRotateRelative(){return this._wheelZAction!==ga.RotateRelative?null:this._wheelZActionCoordinate}set wheelXMoveScene(e){null===e&&this._wheelXAction!==ga.MoveScene||(this._wheelXAction=ga.MoveScene,this._wheelXActionCoordinate=e)}get wheelXMoveScene(){return this._wheelXAction!==ga.MoveScene?null:this._wheelXActionCoordinate}set wheelYMoveScene(e){null===e&&this._wheelYAction!==ga.MoveScene||(this._wheelYAction=ga.MoveScene,this._wheelYActionCoordinate=e)}get wheelYMoveScene(){return this._wheelYAction!==ga.MoveScene?null:this._wheelYActionCoordinate}set wheelZMoveScene(e){null===e&&this._wheelZAction!==ga.MoveScene||(this._wheelZAction=ga.MoveScene,this._wheelZActionCoordinate=e)}get wheelZMoveScene(){return this._wheelZAction!==ga.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=k.Zero();this.camera.getViewMatrix().invertToRef(e);const t=B.Zero();B.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 n=null;switch(t){case ga.MoveRelative:n=this._moveRelative;break;case ga.RotateRelative:n=this._rotateRelative;break;case ga.MoveScene:n=this._moveScene}switch(i){case 0:n.set(e,0,0);break;case 1:n.set(0,e,0);break;case 2:n.set(0,0,e)}}}e([a()],Ra.prototype,"wheelXMoveRelative",null),e([a()],Ra.prototype,"wheelYMoveRelative",null),e([a()],Ra.prototype,"wheelZMoveRelative",null),e([a()],Ra.prototype,"wheelXRotateRelative",null),e([a()],Ra.prototype,"wheelYRotateRelative",null),e([a()],Ra.prototype,"wheelZRotateRelative",null),e([a()],Ra.prototype,"wheelXMoveScene",null),e([a()],Ra.prototype,"wheelYMoveScene",null),e([a()],Ra.prototype,"wheelZMoveScene",null),On.FreeCameraMouseWheelInput=Ra;class Sa{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=Yt.IsSafari()}attachControl(e){e=Yt.BackCompatCameraNoPreventDefault(arguments);let t=null;if(void 0===this._pointerInput&&(this._onLostFocus=()=>{this._offsetX=null,this._offsetY=null},this._pointerInput=i=>{const n=i.event,r="mouse"===n.pointerType||this._isSafari&&void 0===n.pointerType;if(this.allowMouse||!r)if(i.type===cn.POINTERDOWN){if(e||n.preventDefault(),this._pointerPressed.push(n.pointerId),1!==this._pointerPressed.length)return;t={x:n.clientX,y:n.clientY}}else if(i.type===cn.POINTERUP){e||n.preventDefault();const i=this._pointerPressed.indexOf(n.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===cn.POINTERMOVE){if(e||n.preventDefault(),!t)return;if(0!=this._pointerPressed.indexOf(n.pointerId))return;this._offsetX=n.clientX-t.x,this._offsetY=-(n.clientY-t.y)}}),this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,cn.POINTERDOWN|cn.POINTERUP|cn.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();e.cameraRotation.y=t*this._offsetX/this.touchAngularSensibility;if(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 B(0,0,0!==this.touchMoveSensibility?t*this._offsetY/this.touchMoveSensibility:0);k.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,0,e._cameraRotationMatrix),e.cameraDirection.addInPlace(B.TransformCoordinates(i,e._cameraRotationMatrix))}}getClassName(){return"FreeCameraTouchInput"}getSimpleName(){return"touch"}}e([a()],Sa.prototype,"touchAngularSensibility",void 0),e([a()],Sa.prototype,"touchMoveSensibility",void 0),On.FreeCameraTouchInput=Sa;class Ia extends Dn{constructor(e){super(e),this._mouseInput=null,this._mouseWheelInput=null}addKeyboard(){return this.add(new Ta),this}addMouse(e=!0){return this._mouseInput||(this._mouseInput=new Aa(e),this.add(this._mouseInput)),this}removeMouse(){return this._mouseInput&&this.remove(this._mouseInput),this}addMouseWheel(){return this._mouseWheelInput||(this._mouseWheelInput=new Ra,this.add(this._mouseWheelInput)),this}removeMouseWheel(){return this._mouseWheelInput&&this.remove(this._mouseWheelInput),this}addTouch(){return this.add(new Sa),this}clear(){super.clear(),this._mouseInput=null}}class Ca extends bn{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 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 keysUpward(){const e=this.inputs.attached.keyboard;return e?e.keysUpward:[]}set keysUpward(e){const t=this.inputs.attached.keyboard;t&&(t.keysUpward=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 keysDownward(){const e=this.inputs.attached.keyboard;return e?e.keysDownward:[]}set keysDownward(e){const t=this.inputs.attached.keyboard;t&&(t.keysDownward=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 keysRotateLeft(){const e=this.inputs.attached.keyboard;return e?e.keysRotateLeft:[]}set keysRotateLeft(e){const t=this.inputs.attached.keyboard;t&&(t.keysRotateLeft=e)}get keysRotateRight(){const e=this.inputs.attached.keyboard;return e?e.keysRotateRight:[]}set keysRotateRight(e){const t=this.inputs.attached.keyboard;t&&(t.keysRotateRight=e)}get keysRotateUp(){const e=this.inputs.attached.keyboard;return e?e.keysRotateUp:[]}set keysRotateUp(e){const t=this.inputs.attached.keyboard;t&&(t.keysRotateUp=e)}get keysRotateDown(){const e=this.inputs.attached.keyboard;return e?e.keysRotateDown:[]}set keysRotateDown(e){const t=this.inputs.attached.keyboard;t&&(t.keysRotateDown=e)}constructor(e,t,i,n=!0){super(e,t,i,n),this.ellipsoid=new B(.5,1,.5),this.ellipsoidOffset=new B(0,0,0),this.checkCollisions=!1,this.applyGravity=!1,this._needMoveForGravity=!1,this._oldPosition=B.Zero(),this._diffPosition=B.Zero(),this._newPosition=B.Zero(),this._collisionMask=-1,this._onCollisionPositionChange=(e,t,i=null)=>{this._newPosition.copyFrom(t),this._newPosition.subtractToRef(this._oldPosition,this._diffPosition),this._diffPosition.length()>vt.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 Ia(this),this.inputs.addKeyboard().addMouse()}attachControl(e,t){t=Yt.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t)}detachControl(){this.inputs.detachElement(),this.cameraDirection=new B(0,0,0),this.cameraRotation=new U(0,0)}get collisionMask(){return this._collisionMask}set collisionMask(e){this._collisionMask=isNaN(e)?-1:e}_collideWithWorld(e){let t;t=this.parent?B.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 n=e;this.applyGravity&&(n=e.add(this.getScene().gravity)),i.getNewPosition(this._oldPosition,n,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}_checkInputs(){this._localDirection||(this._localDirection=B.Zero(),this._transformedDirection=B.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"}}e([h()],Ca.prototype,"ellipsoid",void 0),e([h()],Ca.prototype,"ellipsoidOffset",void 0),e([a()],Ca.prototype,"checkCollisions",void 0),e([a()],Ca.prototype,"applyGravity",void 0),M("BABYLON.FreeCamera",Ca);class Ma{getClassName(){return"TargetedAnimation"}serialize(){const e={};return e.animation=this.animation.serialize(),e.targetId=this.target.id,e}}class xa{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;e<this._animatables.length;++e){const t=this._animatables[e];!this.mask||this.mask.disabled||this.mask.retainsTarget(t.target.name)?(this._numActiveAnimatables++,t.paused&&t.restart()):t.paused||t.pause()}}else this._numActiveAnimatables=this._targetedAnimations.length}removeUnmaskedAnimations(){if(this.mask&&!this.mask.disabled){for(let e=0;e<this._animatables.length;++e){const t=this._animatables[e];this.mask.retainsTarget(t.target.name)||(t.stop(),this._animatables.splice(e,1),--e)}for(let e=0;e<this._targetedAnimations.length;e++){const t=this._targetedAnimations[e];this.mask.retainsTarget(t.target.name)||(this._targetedAnimations.splice(e,1),--e)}}}get from(){return this._from}set from(e){if(this._from!==e){this._from=e;for(let e=0;e<this._animatables.length;e++){this._animatables[e].fromFrame=this._from}}}get to(){return this._to}set to(e){if(this._to!==e){this._to=e;for(let e=0;e<this._animatables.length;e++){this._animatables[e].toFrame=this._to}}}get isStarted(){return this._isStarted}get isPlaying(){return this._isStarted&&!this._isPaused}get speedRatio(){return this._speedRatio}set speedRatio(e){if(this._speedRatio!==e){this._speedRatio=e;for(let e=0;e<this._animatables.length;e++){this._animatables[e].speedRatio=this._speedRatio}}}get loopAnimation(){return this._loopAnimation}set loopAnimation(e){if(this._loopAnimation!==e){this._loopAnimation=e;for(let e=0;e<this._animatables.length;e++){this._animatables[e].loopAnimation=this._loopAnimation}}}get isAdditive(){return this._isAdditive}set isAdditive(e){if(this._isAdditive!==e){this._isAdditive=e;for(let e=0;e<this._animatables.length;e++){this._animatables[e].isAdditive=this._isAdditive}}}get weight(){return this._weight}set weight(e){this._weight!==e&&(this._weight=e,this.setWeightForAllAnimatables(this._weight))}get targetedAnimations(){return this._targetedAnimations}get animatables(){return this._animatables}get children(){return this._targetedAnimations}get playOrder(){return this._playOrder}set playOrder(e){if(this._playOrder!==e&&(this._playOrder=e,this._animatables.length>0)){for(let e=0;e<this._animatables.length;e++)this._animatables[e].playOrder=this._playOrder;this._scene.sortActiveAnimatables()}}get enableBlending(){return this._enableBlending}set enableBlending(e){if(this._enableBlending!==e&&(this._enableBlending=e,null!==e))for(let t=0;t<this._targetedAnimations.length;++t)this._targetedAnimations[t].animation.enableBlending=e}get blendingSpeed(){return this._blendingSpeed}set blendingSpeed(e){if(this._blendingSpeed!==e&&(this._blendingSpeed=e,null!==e))for(let t=0;t<this._targetedAnimations.length;++t)this._targetedAnimations[t].animation.blendingSpeed=e}getLength(e,t){e=e??this._from;return((t=t??this._to)-e)/(this.targetedAnimations[0].animation.framePerSecond*this._speedRatio)}static MergeAnimationGroups(e,t=!0,i=!1,n){if(0===e.length)return null;n=n??e[0].weight;let r=Number.MAX_VALUE,s=-Number.MAX_VALUE;if(i)for(const t of e)t.from<r&&(r=t.from),t.to>s&&(s=t.to);const a=new xa(e[0].name+"_merged",e[0]._scene,n);for(const n of e){i&&n.normalize(r,s);for(const e of n.targetedAnimations)a.addTargetedAnimation(e.animation,e.target);t&&n.dispose()}return a}constructor(e,t=null,i=-1,n=0){this.name=e,this._targetedAnimations=new Array,this._animatables=new Array,this._from=Number.MAX_VALUE,this._to=-Number.MAX_VALUE,this._speedRatio=1,this._loopAnimation=!1,this._isAdditive=!1,this._weight=-1,this._playOrder=0,this._enableBlending=null,this._blendingSpeed=null,this._numActiveAnimatables=0,this._shouldStart=!0,this._parentContainer=null,this.onAnimationEndObservable=new g,this.onAnimationLoopObservable=new g,this.onAnimationGroupLoopObservable=new g,this.onAnimationGroupEndObservable=new g,this.onAnimationGroupPauseObservable=new g,this.onAnimationGroupPlayObservable=new g,this.metadata=null,this._mask=null,this._animationLoopFlags=[],this._scene=t||y.LastCreatedScene,this._weight=i,this._playOrder=n,this.uniqueId=this._scene.getUniqueId(),this._scene.addAnimationGroup(this)}addTargetedAnimation(e,t){const i=new Ma;i.animation=e,i.target=t;const n=e.getKeys();return this._from>n[0].frame&&(this._from=n[0].frame),this._to<n[n.length-1].frame&&(this._to=n[n.length-1].frame),null!==this._enableBlending&&(e.enableBlending=this._enableBlending),null!==this._blendingSpeed&&(e.blendingSpeed=this._blendingSpeed),this._targetedAnimations.push(i),this._shouldStart=!0,i}removeTargetedAnimation(e){for(let t=this._targetedAnimations.length-1;t>-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;i<this._targetedAnimations.length;i++){const n=this._targetedAnimations[i].animation.getKeys(),r=n[0],s=n[n.length-1];if(r.frame>e){const t={frame:e,value:r.value,inTangent:r.inTangent,outTangent:r.outTangent,interpolation:r.interpolation};n.splice(0,0,t)}if(s.frame<t){const e={frame:t,value:s.value,inTangent:s.inTangent,outTangent:s.outTangent,interpolation:s.interpolation};n.push(e)}}return this._from=e,this._to=t,this}_processLoop(e,t,i){e.onAnimationLoop=()=>{this.onAnimationLoopObservable.notifyObservers(t),this._animationLoopFlags[i]||(this._animationLoopFlags[i]=!0,this._animationLoopCount++,this._animationLoopCount===this._numActiveAnimatables&&(this.onAnimationGroupLoopObservable.notifyObservers(this),this._animationLoopCount=0,this._animationLoopFlags.length=0))}}start(e=!1,t=1,i,n,r){if(this._isStarted||0===this._targetedAnimations.length)return this;this._loopAnimation=e,this._shouldStart=!1,this._animationLoopCount=0,this._animationLoopFlags.length=0;for(let s=0;s<this._targetedAnimations.length;s++){const a=this._targetedAnimations[s],o=this._scene.beginDirectAnimation(a.target,[a.animation],void 0!==i?i:this._from,void 0!==n?n:this._to,e,t,void 0,void 0,void 0!==r?r:this._isAdditive);o.weight=this._weight,o.playOrder=this._playOrder,o.onAnimationEnd=()=>{this.onAnimationEndObservable.notifyObservers(a),this._checkAnimationGroupEnded(o)},this._processLoop(o,a,s),this._animatables.push(o)}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;e<this._animatables.length;e++){this._animatables[e].pause()}return this.onAnimationGroupPauseObservable.notifyObservers(this),this}play(e){return this.isStarted&&this._animatables.length&&!this._shouldStart?(void 0!==e&&(this.loopAnimation=e),this.restart()):(this.stop(),this.start(e,this._speedRatio)),this}reset(){if(!this._isStarted)return this.play(),this.goToFrame(0),this.stop(!0),this;for(let e=0;e<this._animatables.length;e++){this._animatables[e].reset()}return this}restart(){if(!this._isStarted)return this;for(let e=0;e<this._animatables.length;e++){this._animatables[e].restart()}return this.syncWithMask(),this.onAnimationGroupPlayObservable.notifyObservers(this),this._isPaused=!1,this}stop(e=!1){if(!this._isStarted)return this;const t=this._animatables.slice();for(let i=0;i<t.length;i++)t[i].stop(void 0,void 0,!0,e);let i=0;for(let t=0;t<this._scene._activeAnimatables.length;t++){const n=this._scene._activeAnimatables[t];n._runtimeAnimations.length>0?this._scene._activeAnimatables[i++]=n:e&&this._checkAnimationGroupEnded(n,e)}return this._scene._activeAnimatables.length=i,this._isStarted=!1,this}setWeightForAllAnimatables(e){for(let t=0;t<this._animatables.length;t++){this._animatables[t].weight=e}return this}syncAllAnimationsWith(e){for(let t=0;t<this._animatables.length;t++){this._animatables[t].syncWith(e)}return this}goToFrame(e){if(!this._isStarted)return this;for(let t=0;t<this._animatables.length;t++){this._animatables[t].goToFrame(e)}return this}getCurrentFrame(){return this.animatables[0]?.masterFrame||0}dispose(){this.isStarted&&this.stop(),this._targetedAnimations.length=0,this._animatables.length=0;const e=this._scene.animationGroups.indexOf(this);if(e>-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),0===this._animatables.length&&(this._isStarted=!1,t||this.onAnimationGroupEndObservable.notifyObservers(this))}clone(e,t,i=!1){const n=new xa(e||this.name,this._scene,this._weight,this._playOrder);n._from=this.from,n._to=this.to,n._speedRatio=this.speedRatio,n._loopAnimation=this.loopAnimation,n._isAdditive=this.isAdditive,n._enableBlending=this.enableBlending,n._blendingSpeed=this.blendingSpeed,n.metadata=this.metadata,n.mask=this.mask;for(const e of this._targetedAnimations)n.addTargetedAnimation(i?e.animation.clone():e.animation,t?t(e.target):e.target);return n}serialize(){const e={};e.name=this.name,e.from=this.from,e.to=this.to,e.speedRatio=this.speedRatio,e.loopAnimation=this.loopAnimation,e.isAdditive=this.isAdditive,e.weight=this.weight,e.playOrder=this.playOrder,e.enableBlending=this.enableBlending,e.blendingSpeed=this.blendingSpeed,e.targetedAnimations=[];for(let t=0;t<this.targetedAnimations.length;t++){const i=this.targetedAnimations[t];e.targetedAnimations[t]=i.serialize()}return q&&q.HasTags(this)&&(e.tags=q.GetTags(this)),this.metadata&&(e.metadata=this.metadata),e}static Parse(e,t){const i=new xa(e.name,t,e.weight,e.playOrder);for(let n=0;n<e.targetedAnimations.length;n++){const r=e.targetedAnimations[n],s=Cn.Parse(r.animation),a=r.targetId;if("influence"===r.animation.property){const e=t.getMorphTargetById(a);e&&i.addTargetedAnimation(s,e)}else{const e=t.getNodeById(a);null!=e&&i.addTargetedAnimation(s,e)}}return q&&q.AddTagsTo(i,e.tags),null!==e.from&&null!==e.to&&i.normalize(e.from,e.to),void 0!==e.speedRatio&&(i._speedRatio=e.speedRatio),void 0!==e.loopAnimation&&(i._loopAnimation=e.loopAnimation),void 0!==e.isAdditive&&(i._isAdditive=e.isAdditive),void 0!==e.weight&&(i._weight=e.weight),void 0!==e.playOrder&&(i._playOrder=e.playOrder),void 0!==e.enableBlending&&(i._enableBlending=e.enableBlending),void 0!==e.blendingSpeed&&(i._blendingSpeed=e.blendingSpeed),void 0!==e.metadata&&(i.metadata=e.metadata),i}static MakeAnimationAdditive(e,t,i,n=!1,r){let s;s="object"==typeof t?t:{referenceFrame:t,range:i,cloneOriginalAnimationGroup:n,clonedAnimationName:r};let a=e;s.cloneOriginalAnimationGroup&&(a=e.clone(s.clonedAnimationGroupName||a.name));const o=a.targetedAnimations;for(let e=0;e<o.length;e++){const t=o[e];t.animation=Cn.MakeAnimationAdditive(t.animation,s)}if(a.isAdditive=!0,s.clipKeys){let e=Number.MAX_VALUE,t=-Number.MAX_VALUE;const i=a.targetedAnimations;for(let n=0;n<i.length;n++){const r=i[n].animation.getKeys();e>r[0].frame&&(e=r[0].frame),t<r[r.length-1].frame&&(t=r[r.length-1].frame)}a._from=e,a._to=t}return a}static ClipKeys(e,t,i,n,r){const s=e.clone(n||e.name);return xa.ClipKeysInPlace(s,t,i,r)}static ClipKeysInPlace(e,t,i,n){return xa.ClipInPlace(e,t,i,n,!1)}static ClipFrames(e,t,i,n,r){const s=e.clone(n||e.name);return xa.ClipFramesInPlace(s,t,i,r)}static ClipFramesInPlace(e,t,i,n){return xa.ClipInPlace(e,t,i,n,!0)}static ClipInPlace(e,t,i,n,r=!1){let s=Number.MAX_VALUE,a=-Number.MAX_VALUE;const o=e.targetedAnimations;for(let e=0;e<o.length;e++){const l=o[e],c=n?l.animation:l.animation.clone();r&&(c.createKeyForFrame(t),c.createKeyForFrame(i));const h=c.getKeys(),d=[];let u=Number.MAX_VALUE;for(let e=0;e<h.length;e++){const n=h[e];if(!r&&e>=t&&e<=i||r&&n.frame>=t&&n.frame<=i){const e={frame:n.frame,value:n.value.clone?n.value.clone():n.value,inTangent:n.inTangent,outTangent:n.outTangent,interpolation:n.interpolation,lockedTangent:n.lockedTangent};u===Number.MAX_VALUE&&(u=e.frame),e.frame-=u,d.push(e)}}0!==d.length?(s>d[0].frame&&(s=d[0].frame),a<d[d.length-1].frame&&(a=d[d.length-1].frame),c.setKeys(d,!0),l.animation=c):(o.splice(e,1),e--)}return e._from=s,e._to=a,e}getClassName(){return"AnimationGroup"}toString(e){let t="Name: "+this.name;return t+=", type: "+this.getClassName(),e&&(t+=", from: "+this._from,t+=", to: "+this._to,t+=", isStarted: "+this._isStarted,t+=", speedRatio: "+this._speedRatio,t+=", targetedAnimations length: "+this._targetedAnimations.length,t+=", animatables length: "+this._animatables),t}}function ba(e,t,i,n){let r,s=1;n===Ze.TEXTURETYPE_FLOAT?r=new Float32Array(t*i*4):n===Ze.TEXTURETYPE_HALF_FLOAT?(r=new Uint16Array(t*i*4),s=15360):r=n===Ze.TEXTURETYPE_UNSIGNED_INTEGER?new Uint32Array(t*i*4):new Uint8Array(t*i*4);for(let n=0;n<t;n++)for(let a=0;a<i;a++){const i=3*(a*t+n),o=4*(a*t+n);r[o+0]=e[i+0],r[o+1]=e[i+1],r[o+2]=e[i+2],r[o+3]=s}return r}function ya(e){return function(t,i,n,r,s,a,o,l,c=null,h=Ze.TEXTURETYPE_UNSIGNED_INT){const d=e?this._gl.TEXTURE_3D:this._gl.TEXTURE_2D_ARRAY,u=new Et(this,e?10:11);u.baseWidth=i,u.baseHeight=n,u.baseDepth=r,u.width=i,u.height=n,u.depth=r,u.format=s,u.type=h,u.generateMipMaps=a,u.samplingMode=l,e?u.is3D=!0:u.is2DArray=!0,this._doNotHandleContextLost||(u._bufferView=t),e?this.updateRawTexture3D(u,t,s,o,c,h):this.updateRawTexture2DArray(u,t,s,o,c,h),this._bindTextureDirectly(d,u,!0);const f=this._getSamplingParameters(l,a);return this._gl.texParameteri(d,this._gl.TEXTURE_MAG_FILTER,f.mag),this._gl.texParameteri(d,this._gl.TEXTURE_MIN_FILTER,f.min),a&&this._gl.generateMipmap(d),this._bindTextureDirectly(d,null),this._internalTexturesCache.push(u),u}}function Oa(e){return function(t,i,n,r,s=null,a=Ze.TEXTURETYPE_UNSIGNED_INT){const o=e?this._gl.TEXTURE_3D:this._gl.TEXTURE_2D_ARRAY,l=this._getWebGLTextureType(a),c=this._getInternalFormat(n),h=this._getRGBABufferInternalSizedFormat(a,n);this._bindTextureDirectly(o,t,!0),this._unpackFlipY(void 0===r||!!r),this._doNotHandleContextLost||(t._bufferView=i,t.format=n,t.invertY=r,t._compression=s),t.width%4!=0&&this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT,1),s&&i?this._gl.compressedTexImage3D(o,0,this.getCaps().s3tc[s],t.width,t.height,t.depth,0,i):this._gl.texImage3D(o,0,h,t.width,t.height,t.depth,0,c,l,i),t.generateMipMaps&&this._gl.generateMipmap(o),this._bindTextureDirectly(o,null),t.isReady=!0}}Ni.prototype.updateRawTexture=function(e,t,i,n,r=null,s=Ze.TEXTURETYPE_UNSIGNED_INT,a=!1){if(!e)return;const o=this._getRGBABufferInternalSizedFormat(s,i,a),l=this._getInternalFormat(i),c=this._getWebGLTextureType(s);this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0),this._unpackFlipY(void 0===n||!!n),this._doNotHandleContextLost||(e._bufferView=t,e.format=i,e.type=s,e.invertY=n,e._compression=r),e.width%4!=0&&this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT,1),r&&t?this._gl.compressedTexImage2D(this._gl.TEXTURE_2D,0,this.getCaps().s3tc[r],e.width,e.height,0,t):this._gl.texImage2D(this._gl.TEXTURE_2D,0,o,e.width,e.height,0,l,c,t),e.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),e.isReady=!0},Ni.prototype.createRawTexture=function(e,t,i,n,r,s,a,o=null,l=Ze.TEXTURETYPE_UNSIGNED_INT,c=0,h=!1){const d=new Et(this,3);d.baseWidth=t,d.baseHeight=i,d.width=t,d.height=i,d.format=n,d.generateMipMaps=r,d.samplingMode=a,d.invertY=s,d._compression=o,d.type=l,d._useSRGBBuffer=this._getUseSRGBBuffer(h,!r),this._doNotHandleContextLost||(d._bufferView=e),this.updateRawTexture(d,e,n,s,o,l,d._useSRGBBuffer),this._bindTextureDirectly(this._gl.TEXTURE_2D,d,!0);const u=this._getSamplingParameters(a,r);return this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MAG_FILTER,u.mag),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MIN_FILTER,u.min),r&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._internalTexturesCache.push(d),d},Ni.prototype.createRawCubeTexture=function(e,t,i,n,r,s,a,o=null){const l=this._gl,c=new Et(this,8);c.isCube=!0,c.format=i,c.type=n,this._doNotHandleContextLost||(c._bufferViewArray=e);const h=this._getWebGLTextureType(n);let d=this._getInternalFormat(i);d===l.RGB&&(d=l.RGBA),h!==l.FLOAT||this._caps.textureFloatLinearFiltering?h!==this._gl.HALF_FLOAT_OES||this._caps.textureHalfFloatLinearFiltering?h!==l.FLOAT||this._caps.textureFloatRender?h!==l.HALF_FLOAT||this._caps.colorBufferFloat||(r=!1,de.Warn("Render to half float textures is not supported. Mipmap generation forced to false.")):(r=!1,de.Warn("Render to float textures is not supported. Mipmap generation forced to false.")):(r=!1,a=Ze.TEXTURE_NEAREST_SAMPLINGMODE,de.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.")):(r=!1,a=Ze.TEXTURE_NEAREST_SAMPLINGMODE,de.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively."));const u=t,f=u;c.width=u,c.height=f,c.invertY=s,c._compression=o;if(!this.needPOTTextures||Vt(c.width)&&Vt(c.height)||(r=!1),e)this.updateRawCubeTexture(c,e,i,n,s,o);else{const e=this._getRGBABufferInternalSizedFormat(n),t=0;this._bindTextureDirectly(l.TEXTURE_CUBE_MAP,c,!0);for(let i=0;i<6;i++)o?l.compressedTexImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+i,t,this.getCaps().s3tc[o],c.width,c.height,0,void 0):l.texImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+i,t,e,c.width,c.height,0,d,h,null);this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)}this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,c,!0),e&&r&&this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);const _=this._getSamplingParameters(a,r);return l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_MAG_FILTER,_.mag),l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_MIN_FILTER,_.min),l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_WRAP_S,l.CLAMP_TO_EDGE),l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_WRAP_T,l.CLAMP_TO_EDGE),this._bindTextureDirectly(l.TEXTURE_CUBE_MAP,null),c.generateMipMaps=r,c.samplingMode=a,c.isReady=!0,c},Ni.prototype.updateRawCubeTexture=function(e,t,i,n,r,s=null,a=0){e._bufferViewArray=t,e.format=i,e.type=n,e.invertY=r,e._compression=s;const o=this._gl,l=this._getWebGLTextureType(n);let c=this._getInternalFormat(i);const h=this._getRGBABufferInternalSizedFormat(n);let d=!1;c===o.RGB&&(c=o.RGBA,d=!0),this._bindTextureDirectly(o.TEXTURE_CUBE_MAP,e,!0),this._unpackFlipY(void 0===r||!!r),e.width%4!=0&&o.pixelStorei(o.UNPACK_ALIGNMENT,1);for(let i=0;i<6;i++){let r=t[i];s?o.compressedTexImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+i,a,this.getCaps().s3tc[s],e.width,e.height,0,r):(d&&(r=ba(r,e.width,e.height,n)),o.texImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+i,a,h,e.width,e.height,0,c,l,r))}(!this.needPOTTextures||Vt(e.width)&&Vt(e.height))&&e.generateMipMaps&&0===a&&this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),e.isReady=!0},Ni.prototype.createRawCubeTextureFromUrl=function(e,t,i,n,r,s,a,o,l=null,c=null,h=Ze.TEXTURE_TRILINEAR_SAMPLINGMODE,d=!1){const u=this._gl,f=this.createRawCubeTexture(null,i,n,r,!s,d,h,null);t?.addPendingData(f),f.url=e,f.isReady=!1,this._internalTexturesCache.push(f);const _=e=>{const i=f.width,s=a(e);if(s){if(o){const e=this._getWebGLTextureType(r);let t=this._getInternalFormat(n);const a=this._getRGBABufferInternalSizedFormat(r);let l=!1;t===u.RGB&&(t=u.RGBA,l=!0),this._bindTextureDirectly(u.TEXTURE_CUBE_MAP,f,!0),this._unpackFlipY(!1);const c=o(s);for(let n=0;n<c.length;n++){const s=i>>n;for(let i=0;i<6;i++){let o=c[n][i];l&&(o=ba(o,s,s,r)),u.texImage2D(i,n,a,s,s,0,t,e,o)}}this._bindTextureDirectly(u.TEXTURE_CUBE_MAP,null)}else this.updateRawCubeTexture(f,s,n,r,d);f.isReady=!0,t?.removePendingData(f),f.onLoadedObservable.notifyObservers(f),f.onLoadedObservable.clear(),l&&l()}};return this._loadFile(e,(e=>{_(e)}),void 0,t?.offlineProvider,!0,((e,i)=>{t?.removePendingData(f),c&&e&&c(e.status+" "+e.statusText,i)})),f},Ni.prototype.createRawTexture2DArray=ya(!1),Ni.prototype.createRawTexture3D=ya(!0),Ni.prototype.updateRawTexture2DArray=Oa(!1),Ni.prototype.updateRawTexture3D=Oa(!0);class Da extends Pr{constructor(e,t,i,n,r,s=!0,a=!1,o=Ze.TEXTURE_TRILINEAR_SAMPLINGMODE,l=Ze.TEXTURETYPE_UNSIGNED_INT,c,h){super(null,r,!s,a,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,c),this.format=n,this._engine&&(this._engine._caps.textureFloatLinearFiltering||l!==Ze.TEXTURETYPE_FLOAT||(o=Ze.TEXTURE_NEAREST_SAMPLINGMODE),this._engine._caps.textureHalfFloatLinearFiltering||l!==Ze.TEXTURETYPE_HALF_FLOAT||(o=Ze.TEXTURE_NEAREST_SAMPLINGMODE),this._texture=this._engine.createRawTexture(e,t,i,n,s,a,o,null,l,c??0,h??!1),this.wrapU=Pr.CLAMP_ADDRESSMODE,this.wrapV=Pr.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 Da(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,n,r=!0,s=!1,a=Ze.TEXTURE_TRILINEAR_SAMPLINGMODE){return new Da(e,t,i,Ze.TEXTUREFORMAT_LUMINANCE,n,r,s,a)}static CreateLuminanceAlphaTexture(e,t,i,n,r=!0,s=!1,a=Ze.TEXTURE_TRILINEAR_SAMPLINGMODE){return new Da(e,t,i,Ze.TEXTUREFORMAT_LUMINANCE_ALPHA,n,r,s,a)}static CreateAlphaTexture(e,t,i,n,r=!0,s=!1,a=Ze.TEXTURE_TRILINEAR_SAMPLINGMODE){return new Da(e,t,i,Ze.TEXTUREFORMAT_ALPHA,n,r,s,a)}static CreateRGBTexture(e,t,i,n,r=!0,s=!1,a=Ze.TEXTURE_TRILINEAR_SAMPLINGMODE,o=Ze.TEXTURETYPE_UNSIGNED_INT,l=0,c=!1){return new Da(e,t,i,Ze.TEXTUREFORMAT_RGB,n,r,s,a,o,l,c)}static CreateRGBATexture(e,t,i,n,r=!0,s=!1,a=Ze.TEXTURE_TRILINEAR_SAMPLINGMODE,o=Ze.TEXTURETYPE_UNSIGNED_INT,l=0,c=!1){return new Da(e,t,i,Ze.TEXTUREFORMAT_RGBA,n,r,s,a,o,l,c)}static CreateRGBAStorageTexture(e,t,i,n,r=!0,s=!1,a=Ze.TEXTURE_TRILINEAR_SAMPLINGMODE,o=Ze.TEXTURETYPE_UNSIGNED_INT,l=!1){return new Da(e,t,i,Ze.TEXTUREFORMAT_RGBA,n,r,s,a,o,Ze.TEXTURE_CREATIONFLAG_STORAGE,l)}static CreateRTexture(e,t,i,n,r=!0,s=!1,a=Pr.TRILINEAR_SAMPLINGMODE,o=Ze.TEXTURETYPE_FLOAT){return new Da(e,t,i,Ze.TEXTUREFORMAT_R,n,r,s,a,o)}static CreateRStorageTexture(e,t,i,n,r=!0,s=!1,a=Pr.TRILINEAR_SAMPLINGMODE,o=Ze.TEXTURETYPE_FLOAT){return new Da(e,t,i,Ze.TEXTUREFORMAT_R,n,r,s,a,o,Ze.TEXTURE_CREATIONFLAG_STORAGE)}}class Na{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=k.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 g,this.bones=[],this._scene=i||y.LastCreatedScene,this._uniqueId=this._scene.getUniqueId(),this._scene.addSkeleton(this),this._isDirty=!0;const n=this._scene.getEngine().getCaps();this._canUseTextureForBones=n.textureFloat&&n.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<i;t++)if(this.bones[t].name===e)return t;return-1}createAnimationRange(e,t,i){if(!this._ranges[e]){this._ranges[e]=new pn(e,t,i);for(let n=0,r=this.bones.length;n<r;n++)this.bones[n].animations[0]&&this.bones[n].animations[0].createRange(e,t,i)}}deleteAnimationRange(e,t=!0){for(let i=0,n=this.bones.length;i<n;i++)this.bones[i].animations[0]&&this.bones[i].animations[0].deleteRange(e,t);this._ranges[e]=null}getAnimationRange(e){return this._ranges[e]||null}getAnimationRanges(){const e=[];let t;for(t in this._ranges)e.push(this._ranges[t]);return e}copyAnimationRange(e,t,i=!1){if(this._ranges[t]||!e.getAnimationRange(t))return!1;let n=!0;const r=this._getHighestAnimationFrame()+1,s={},a=e.bones;let o,l;for(l=0,o=a.length;l<o;l++)s[a[l].name]=a[l];this.bones.length!==a.length&&(de.Warn(`copyAnimationRange: this rig has ${this.bones.length} bones, while source as ${a.length}`),n=!1);const c=i&&this.dimensionsAtRest&&e.dimensionsAtRest?this.dimensionsAtRest.divide(e.dimensionsAtRest):null;for(l=0,o=this.bones.length;l<o;l++){const e=this.bones[l].name,a=s[e];a?n=n&&this.bones[l].copyAnimationRange(a,t,r,i,c):(de.Warn("copyAnimationRange: not same rig, missing source bone "+e),n=!1)}const h=e.getAnimationRange(t);return h&&(this._ranges[t]=new pn(t,h.from+r,h.to+r)),n}returnToRest(){for(const e of this.bones)-1!==e._index&&e.returnToRest()}_getHighestAnimationFrame(){let e=0;for(let t=0,i=this.bones.length;t<i;t++)if(this.bones[t].animations[0]){const i=this.bones[t].animations[0].getHighestFrame();e<i&&(e=i)}return e}beginAnimation(e,t,i,n){const r=this.getAnimationRange(e);return r?this._scene.beginAnimation(this,r.from,r.to,t,i,n):null}static MakeAnimationAdditive(e,t=0,i){const n=e.getAnimationRange(i);if(!n)return null;const r=e._scene.getAllAnimatablesByTarget(e);let s=null;for(let e=0;e<r.length;e++){const t=r[e];if(t.fromFrame===n?.from&&t.toFrame===n?.to){s=t;break}}const a=e.getAnimatables();for(let e=0;e<a.length;e++){const n=a[e].animations;if(n)for(let e=0;e<n.length;e++)Cn.MakeAnimationAdditive(n[e],t,i)}return s&&(s.isAdditive=!0),e}_markAsDirty(){this._isDirty=!0,this._absoluteTransformIsDirty=!0}_registerMeshWithPoseMatrix(e){this._meshesWithPoseMatrix.push(e)}_unregisterMeshWithPoseMatrix(e){const t=this._meshesWithPoseMatrix.indexOf(e);t>-1&&this._meshesWithPoseMatrix.splice(t,1)}_computeTransformMatrices(e,t){this.onBeforeComputeObservable.notifyObservers(this);for(let i=0;i<this.bones.length;i++){const n=this.bones[i];n._childUpdateId++;const r=n.getParent();if(r?n.getLocalMatrix().multiplyToRef(r.getFinalMatrix(),n.getFinalMatrix()):t?n.getLocalMatrix().multiplyToRef(t,n.getFinalMatrix()):n.getFinalMatrix().copyFrom(n.getLocalMatrix()),-1!==n._index){const t=null===n._index?i:n._index;n.getAbsoluteInverseBindMatrix().multiplyToArray(n.getFinalMatrix(),e,16*t)}}this._identity.copyToArray(e,16*this.bones.length)}prepare(e=!1){if(!e){const e=this.getScene().getRenderId();if(this._currentRenderId===e)return;this._currentRenderId=e}if(this._numBonesWithLinkedTransformNode>0)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)if(!e.getParent()){e.getBindMatrix().multiplyToRef(t,H.Matrix[1]),e._updateAbsoluteBindMatrices(H.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=Da.CreateRGBATexture(e._bonesTransformMatrices,4*(this.bones.length+1),1,this._scene,!1,!1,Ze.TEXTURE_NEAREST_SAMPLINGMODE,Ze.TEXTURETYPE_FLOAT))}}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=Da.CreateRGBATexture(this._transformMatrices,4*(this.bones.length+1),1,this._scene,!1,!1,Ze.TEXTURE_NEAREST_SAMPLINGMODE,Ze.TEXTURETYPE_FLOAT))),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<this.bones.length;e++)this._animatables.push(this.bones[e])}return this._animatables}clone(e,t){const i=new Na(e,t||e,this._scene);i.needInitialSkinMatrix=this.needInitialSkinMatrix;for(let e=0;e<this.bones.length;e++){const t=this.bones[e];let n=null;const r=t.getParent();if(r){const e=this.bones.indexOf(r);n=i.bones[e]}const s=new la(t.name,i,n,t.getBindMatrix().clone(),t.getRestMatrix().clone());s._index=t._index,t._linkedTransformNode&&s.linkTransformNode(t._linkedTransformNode),fe.DeepCopy(t.animations,s.animations)}if(this._ranges){i._ranges={};for(const e in this._ranges){const t=this._ranges[e];t&&(i._ranges[e]=t.clone())}}return this._isDirty=!0,i.prepare(!0),i}enableBlending(e=.01){this.bones.forEach((t=>{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;t<this.bones.length;t++){const i=this.bones[t],n=i.getParent(),r={parentBoneIndex:n?this.bones.indexOf(n):-1,index:i.getIndex(),name:i.name,id:i.id,matrix:i.getBindMatrix().asArray(),rest:i.getRestMatrix().asArray(),linkedTransformNodeId:i.getTransformNode()?.id};e.bones.push(r),i.length&&(r.length=i.length),i.metadata&&(r.metadata=i.metadata),i.animations&&i.animations.length>0&&(r.animation=i.animations[0].serialize()),e.ranges=[];for(const t in this._ranges){const i=this._ranges[t];if(!i)continue;const n={};n.name=t,n.from=i.from,n.to=i.to,e.ranges.push(n)}}return e}static Parse(e,t){const i=new Na(e.name,e.id,t);let n;for(e.dimensionsAtRest&&(i.dimensionsAtRest=B.FromArray(e.dimensionsAtRest)),i.needInitialSkinMatrix=e.needInitialSkinMatrix,n=0;n<e.bones.length;n++){const t=e.bones[n],r=e.bones[n].index;let s=null;t.parentBoneIndex>-1&&(s=i.bones[t.parentBoneIndex]);const a=t.rest?k.FromArray(t.rest):null,o=new la(t.name,i,s,k.FromArray(t.matrix),a,null,r);void 0!==t.id&&null!==t.id&&(o.id=t.id),t.length&&(o.length=t.length),t.metadata&&(o.metadata=t.metadata),t.animation&&o.animations.push(Cn.Parse(t.animation)),void 0!==t.linkedTransformNodeId&&null!==t.linkedTransformNodeId&&(i._hasWaitingData=!0,o._waitingTransformNodeId=t.linkedTransformNodeId)}if(e.ranges)for(n=0;n<e.ranges.length;n++){const t=e.ranges[n];i.createAnimationRange(t.name,t.from,t.to)}return i}computeAbsoluteMatrices(e=!1){(this._absoluteTransformIsDirty||e)&&(this.bones[0].computeAbsoluteMatrices(),this._absoluteTransformIsDirty=!1)}computeAbsoluteTransforms(e=!1){this.computeAbsoluteMatrices(e)}getPoseMatrix(){let e=null;return this._meshesWithPoseMatrix.length>0&&(e=this._meshesWithPoseMatrix[0].getPoseMatrix()),e}sortBones(){const e=[],t=new Array(this.bones.length);for(let i=0;i<this.bones.length;i++)this._sortBones(i,e,t);this.bones=e}_sortBones(e,t,i){if(i[e])return;i[e]=!0;const n=this.bones[e];if(!n)return;void 0===n._index&&(n._index=e);const r=n.getParent();r&&this._sortBones(this.bones.indexOf(r),t,i),t.push(n)}setCurrentPoseAsRest(){this.bones.forEach((e=>{e.setCurrentPoseAsRest()}))}}class Pa{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 g,this._onDataLayoutChanged=new g,this._animationPropertiesOverride=null,this._scene=i||y.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=re.Clone((()=>new Pa(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())),re.AppendSerializedAnimations(this,e),e}getClassName(){return"MorphTarget"}static Parse(e,t){const i=new Pa(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;t<e.animations.length;t++){const n=e.animations[t],r=x("BABYLON.Animation");r&&i.animations.push(r.Parse(n))}e.autoAnimate&&t&&t.beginAnimation(i,e.autoAnimateFrom,e.autoAnimateTo,e.autoAnimateLoop,e.autoAnimateSpeed||1)}return i}static FromMesh(e,t,i){t||(t=e.name);const n=new Pa(t,i,e.getScene());return n.setPositions(e.getVerticesData(si.PositionKind)),e.isVerticesDataPresent(si.NormalKind)&&n.setNormals(e.getVerticesData(si.NormalKind)),e.isVerticesDataPresent(si.TangentKind)&&n.setTangents(e.getVerticesData(si.TangentKind)),e.isVerticesDataPresent(si.UVKind)&&n.setUVs(e.getVerticesData(si.UVKind)),n}}e([a()],Pa.prototype,"id",void 0);class La extends Pr{get depth(){return this._depth}constructor(e,t,i,n,r,s,a=!0,o=!1,l=Pr.TRILINEAR_SAMPLINGMODE,c=Ze.TEXTURETYPE_UNSIGNED_INT,h){super(null,s,!a,o),this.format=r,this._texture=s.getEngine().createRawTexture2DArray(e,t,i,n,r,a,o,l,null,c,h),this._depth=n,this.is2DArray=!0}update(e){this._texture&&this._getEngine().updateRawTexture2DArray(this._texture,e,this._texture.format,this._texture.invertY,null,this._texture.type)}static CreateRGBATexture(e,t,i,n,r,s=!0,a=!1,o=Ze.TEXTURE_TRILINEAR_SAMPLINGMODE,l=Ze.TEXTURETYPE_UNSIGNED_INT){return new La(e,t,i,n,Ze.TEXTUREFORMAT_RGBA,r,s,a,o,l)}}class Fa{set areUpdatesFrozen(e){e?this._blockCounter++:(this._blockCounter--,this._blockCounter<=0&&(this._blockCounter=0,this._syncActiveTargets(!0)))}get areUpdatesFrozen(){return this._blockCounter>0}constructor(e=null){if(this._targets=new Array,this._targetInfluenceChangedObservers=new Array,this._targetDataLayoutChangedObservers=new Array,this._activeTargets=new Zt(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=y.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 Fa.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 Fa(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>=Fa.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 n=e.getPositions();if(n){const e=n.length/3;if(0===this._vertexCount)this._vertexCount=e;else if(this._vertexCount!==e)return void de.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;e<t;e++)this._influences[e]=this._tempInfluences[e];e&&this.synchronize()}synchronize(){if(this._scene&&!this.areUpdatesFrozen){if(this.isUsingTextureForTargets&&(this._vertexCount||this.numMaxInfluencers>0)){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 n=0;n<e;n++){const e=this._targets[n],r=e.getPositions(),s=e.getNormals(),a=e.getUVs(),o=e.getTangents();if(!r)return void(0===n&&de.Error("Invalid morph target. Target must have positions."));i=n*this._textureWidth*this._textureHeight*4;for(let e=0;e<this._vertexCount;e++)t[i]=r[3*e],t[i+1]=r[3*e+1],t[i+2]=r[3*e+2],i+=4,this._supportsNormals&&s&&(t[i]=s[3*e],t[i+1]=s[3*e+1],t[i+2]=s[3*e+2],i+=4),this._supportsUVs&&a&&(t[i]=a[2*e],t[i+1]=a[2*e+1],i+=4),this._supportsTangents&&o&&(t[i]=o[3*e],t[i+1]=o[3*e+1],t[i+2]=o[3*e+2],i+=4)}this._targetStoreTexture=La.CreateRGBATexture(t,this._textureWidth,this._textureHeight,e,this._scene,!1,!1,Ze.TEXTURE_NEAREST_SAMPLINGMODE,Ze.TEXTURETYPE_FLOAT)}}for(const e of this._scene.meshes)e.morphTargetManager===this&&e._syncGeometryWithMorphTargetManager()}}dispose(){if(this._targetStoreTexture&&this._targetStoreTexture.dispose(),this._targetStoreTexture=null,this._scene){if(this._scene.removeMorphTargetManager(this),this._parentContainer){const e=this._parentContainer.morphTargetManagers.indexOf(this);e>-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 Fa(t);i._uniqueId=e.id;for(const n of e.targets)i.addTarget(Pa.Parse(n,t));return i}}Fa.EnableTextureStorage=!0,Fa.MaxActiveMorphTargetsInVertexAttributeMode=8,ln._instancedMeshFactory=(e,t)=>{const i=new wa(e,t);if(t.instancedBuffers){i.instancedBuffers={};for(const e in t.instancedBuffers)i.instancedBuffers[e]=t.instancedBuffers[e]}return i};class wa extends Vi{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&&Yt.Warn("Setting receiveShadows on an instanced mesh has no effect")}get material(){return this._sourceMesh.material}set material(e){this._sourceMesh?.material!==e&&Yt.Warn("Setting material on an instanced mesh has no effect")}get visibility(){return this._sourceMesh.visibility}set visibility(e){this._sourceMesh?.visibility!==e&&Yt.Warn("Setting visibility on an instanced mesh has no effect")}get skeleton(){return this._sourceMesh.skeleton}set skeleton(e){this._sourceMesh?.skeleton!==e&&Yt.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&&de.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene")}getTotalVertices(){return this._sourceMesh?this._sourceMesh.getTotalVertices():0}getTotalIndices(){return this._sourceMesh.getTotalIndices()}get sourceMesh(){return this._sourceMesh}createInstance(e){return this._sourceMesh.createInstance(e)}isReady(e=!1){return this._sourceMesh.isReady(e,!0)}getVerticesData(e,t,i){return this._sourceMesh.getVerticesData(e,t,i)}copyVerticesData(e,t){this._sourceMesh.copyVerticesData(e,t)}setVerticesData(e,t,i,n){return this.sourceMesh&&this.sourceMesh.setVerticesData(e,t,i,n),this.sourceMesh}updateVerticesData(e,t,i,n){return this.sourceMesh&&this.sourceMesh.updateVerticesData(e,t,i,n),this.sourceMesh}setIndices(e,t=null){return this.sourceMesh&&this.sourceMesh.setIndices(e,t),this.sourceMesh}isVerticesDataPresent(e){return this._sourceMesh.isVerticesDataPresent(e)}getIndices(){return this._sourceMesh.getIndices()}get _positions(){return this._sourceMesh._positions}refreshBoundingInfo(e=!1,t=!1){if(this.hasBoundingInfo&&this.getBoundingInfo().isLocked)return this;let i;i="object"==typeof e?e:{applySkeleton:e,applyMorph:t};const n=this._sourceMesh.geometry?this._sourceMesh.geometry.boundingBias:null;return this._refreshBoundingInfo(this._sourceMesh._getData(i,null,si.PositionKind),n),this}_preActivate(){return this._currentLOD&&this._currentLOD._preActivate(),this}_activate(e,t){if(super._activate(e,t),this._sourceMesh.subMeshes||de.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!==Si.BILLBOARDMODE_NONE&&this._currentLOD._masterMesh!==this){this._billboardWorldMatrix||(this._billboardWorldMatrix=new k);const e=this._currentLOD._masterMesh;return this._currentLOD._masterMesh=this,H.Vector3[7].copyFrom(this._currentLOD.position),this._currentLOD.position.set(0,0,0),this._billboardWorldMatrix.copyFrom(this._currentLOD.computeWorldMatrix(!0)),this._currentLOD.position.copyFrom(H.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;e<this._sourceMesh.subMeshes.length;e++)this._sourceMesh.subMeshes[e].clone(this,this._sourceMesh);return this}_generatePointsArray(){return this._sourceMesh._generatePointsArray()}_updateBoundingInfo(){return this.hasBoundingInfo?this.getBoundingInfo().update(this.worldMatrixFromCache):this.buildBoundingInfo(this.absolutePosition,this.absolutePosition,this.worldMatrixFromCache),this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache),this}clone(e,t=null,i,n){const r=(n||this._sourceMesh).createInstance(e);if(fe.DeepCopy(this,r,["name","subMeshes","uniqueId","parent","lightSources","receiveShadows","material","visibility","skeleton","sourceMesh","isAnInstance","facetNb","isFacetDataEnabled","isBlocked","useBones","hasInstances","collider","edgesRenderer","forward","up","right","absolutePosition","absoluteScaling","absoluteRotationQuaternion","isWorldMatrixFrozen","nonUniformScaling","behaviors","worldMatrixFromCache","hasThinInstances","hasBoundingInfo"],[]),this.refreshBoundingInfo(),t&&(r.parent=t),!i)for(let e=0;e<this.getScene().meshes.length;e++){const t=this.getScene().meshes[e];t.parent===this&&t.clone(t.name,r)}return r.computeWorldMatrix(!0),this.onClonedObservable.notifyObservers(r),r}dispose(e,t=!1){this._sourceMesh.removeInstance(this),super.dispose(e,t)}_serializeAsParent(e){super._serializeAsParent(e),e.parentId=this._sourceMesh.uniqueId,e.parentInstanceIndex=this._indexInSourceMeshInstanceArray}instantiateHierarchy(e=null,t,i){const n=this.clone("Clone of "+(this.name||this.id),e||this.parent,!0,t&&t.newSourcedMesh);n&&i&&i(this,n);for(const e of this.getChildTransformNodes(!0))e.instantiateHierarchy(n,t,i);return n}}ln.prototype.registerInstancedBuffer=function(e,t){if(this._userInstancedBuffersStorage?.vertexBuffers[e]?.dispose(),!this.instancedBuffers){this.instancedBuffers={};for(const e of this.instances)e.instancedBuffers={}}this._userInstancedBuffersStorage||(this._userInstancedBuffersStorage={data:{},vertexBuffers:{},strides:{},sizes:{},vertexArrayObjects:this.getEngine().getCaps().vertexArrayObject?{}:void 0}),this.instancedBuffers[e]=null,this._userInstancedBuffersStorage.strides[e]=t,this._userInstancedBuffersStorage.sizes[e]=32*t,this._userInstancedBuffersStorage.data[e]=new Float32Array(this._userInstancedBuffersStorage.sizes[e]),this._userInstancedBuffersStorage.vertexBuffers[e]=new si(this.getEngine(),this._userInstancedBuffersStorage.data[e],e,!0,!1,t,!0);for(const t of this.instances)t.instancedBuffers[e]=null;this._invalidateInstanceVertexArrayObject(),this._markSubMeshesAsAttributesDirty()},ln.prototype._processInstancedBuffers=function(e,t){const i=e?e.length:0;for(const n in this.instancedBuffers){let r=this._userInstancedBuffersStorage.sizes[n];const s=this._userInstancedBuffersStorage.strides[n],a=(i+1)*s;for(;r<a;)r*=2;this._userInstancedBuffersStorage.data[n].length!=r&&(this._userInstancedBuffersStorage.data[n]=new Float32Array(r),this._userInstancedBuffersStorage.sizes[n]=r,this._userInstancedBuffersStorage.vertexBuffers[n]&&(this._userInstancedBuffersStorage.vertexBuffers[n].dispose(),this._userInstancedBuffersStorage.vertexBuffers[n]=null));const o=this._userInstancedBuffersStorage.data[n];let l=0;if(t){const e=this.instancedBuffers[n];e.toArray?e.toArray(o,l):e.copyToArray?e.copyToArray(o,l):o[l]=e,l+=s}for(let t=0;t<i;t++){const i=e[t].instancedBuffers[n];i.toArray?i.toArray(o,l):i.copyToArray?i.copyToArray(o,l):o[l]=i,l+=s}this._userInstancedBuffersStorage.vertexBuffers[n]?this._userInstancedBuffersStorage.vertexBuffers[n].updateDirectly(o,0):(this._userInstancedBuffersStorage.vertexBuffers[n]=new si(this.getEngine(),this._userInstancedBuffersStorage.data[n],n,!0,!1,s,!0),this._invalidateInstanceVertexArrayObject())}},ln.prototype._invalidateInstanceVertexArrayObject=function(){if(this._userInstancedBuffersStorage&&void 0!==this._userInstancedBuffersStorage.vertexArrayObjects){for(const e in this._userInstancedBuffersStorage.vertexArrayObjects)this.getEngine().releaseVertexArrayObject(this._userInstancedBuffersStorage.vertexArrayObjects[e]);this._userInstancedBuffersStorage.vertexArrayObjects={}}},ln.prototype._disposeInstanceSpecificData=function(){for(this._instanceDataStorage.instancesBuffer&&(this._instanceDataStorage.instancesBuffer.dispose(),this._instanceDataStorage.instancesBuffer=null);this.instances.length;)this.instances[0].dispose();for(const e in this.instancedBuffers)this._userInstancedBuffersStorage.vertexBuffers[e]&&this._userInstancedBuffersStorage.vertexBuffers[e].dispose();this._invalidateInstanceVertexArrayObject(),this.instancedBuffers={}},M("BABYLON.InstancedMesh",wa);class Ua extends zn{}class Ba{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 Ga extends zn{constructor(e){super(),this._wasAddedToScene=!1,(e=e||y.LastCreatedScene)&&(this.scene=e,this.sounds=[],this.effectLayers=[],this.layers=[],this.lensFlareSystems=[],this.proceduralTextures=[],this.reflectionProbes=[],e.onDisposeObservable.add((()=>{this._wasAddedToScene||this.dispose()})),this._onContextRestoredObserver=e.getEngine().onContextRestoredObservable.add((()=>{for(const 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 n of e){const e=n.uniqueId,r=i.dependsOn.get(e);if(n instanceof wa){const s=n.sourceMesh;t.has(s.uniqueId)&&(r.add(s.uniqueId),i.dependedBy.get(s.uniqueId).add(e))}const s=i.dependedBy.get(e);for(const r of n.getDescendants()){const n=r.uniqueId;if(t.has(n)){s.add(n);i.dependsOn.get(n).add(e)}}}const n=[],r=[];for(const n of e){const e=n.uniqueId;0===i.dependsOn.get(e).size&&(r.push(n),t.delete(e))}const s=r;for(;s.length>0;){const e=s.shift();n.push(e);const r=i.dependedBy.get(e.uniqueId);for(const n of Array.from(r.values())){const r=i.dependsOn.get(n);r.delete(e.uniqueId),0===r.size&&t.get(n)&&(s.push(t.get(n)),t.delete(n))}}return t.size>0&&(de.Error("SceneSerializer._topologicalSort: There were unvisited nodes:"),t.forEach((e=>de.Error(e.name)))),n}_addNodeAndDescendantsToList(e,t,i,n){if(i&&(!n||n(i))&&!t.has(i.uniqueId)){e.push(i),t.add(i.uniqueId);for(const r of i.getDescendants(!0))this._addNodeAndDescendantsToList(e,t,r,n)}}_isNodeInContainer(e){return e instanceof Vi&&-1!==this.meshes.indexOf(e)||(e instanceof Si&&-1!==this.transformNodes.indexOf(e)||(e instanceof Xn&&-1!==this.lights.indexOf(e)||e instanceof ii&&-1!==this.cameras.indexOf(e)))}_isValidHierarchy(){for(const e of this.meshes)if(e.parent&&!this._isNodeInContainer(e.parent))return de.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 de.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 de.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 de.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;return!0}instantiateModelsToScene(e,t=!1,i){this._isValidHierarchy()||Yt.Warn("SceneSerializer.InstantiateModelsToScene: The Asset Container hierarchy is not valid.");const n={},r={},s=new Ba,a=[],o=[],l={doNotInstantiate:!0,...i},c=[],h=new Set;for(const e of this.transformNodes)null===e.parent&&this._addNodeAndDescendantsToList(c,h,e,l.predicate);for(const e of this.meshes)null===e.parent&&this._addNodeAndDescendantsToList(c,h,e,l.predicate);const d=this._topologicalSort(c),u=(i,a)=>{if(((t,i)=>{if(n[t.uniqueId]=i.uniqueId,r[i.uniqueId]=i,e&&(i.name=e(t.name)),i instanceof ln){const e=i;if(e.morphTargetManager){const i=t.morphTargetManager;e.morphTargetManager=i.clone();for(let t=0;t<i.numTargets;t++){const s=i.getTarget(t),a=e.morphTargetManager.getTarget(t);n[s.uniqueId]=a.uniqueId,r[a.uniqueId]=a}}}})(i,a),i.parent){const e=n[i.parent.uniqueId],t=r[e];a.parent=t||i.parent}if(a.position&&i.position&&a.position.copyFrom(i.position),a.rotationQuaternion&&i.rotationQuaternion&&a.rotationQuaternion.copyFrom(i.rotationQuaternion),a.rotation&&i.rotation&&a.rotation.copyFrom(i.rotation),a.scaling&&i.scaling&&a.scaling.copyFrom(i.scaling),a.material){const s=a;if(s.material)if(t){const t=i.material;if(-1===o.indexOf(t)){let i=t.clone(e?e(t.name):"Clone of "+t.name);if(o.push(t),n[t.uniqueId]=i.uniqueId,r[i.uniqueId]=i,"MultiMaterial"===t.getClassName()){const s=t;for(const t of s.subMaterials)t&&(i=t.clone(e?e(t.name):"Clone of "+t.name),o.push(t),n[t.uniqueId]=i.uniqueId,r[i.uniqueId]=i);s.subMaterials=s.subMaterials.map((e=>e&&r[n[e.uniqueId]]))}}"InstancedMesh"!==s.getClassName()&&(s.material=r[n[t.uniqueId]])}else"MultiMaterial"===s.material.getClassName()?-1===this.scene.multiMaterials.indexOf(s.material)&&this.scene.addMultiMaterial(s.material):-1===this.scene.materials.indexOf(s.material)&&this.scene.addMaterial(s.material)}null===a.parent&&s.rootNodes.push(a)};return d.forEach((e=>{if("InstancedMesh"===e.getClassName()){const t=e,i=t.sourceMesh,s=n[i.uniqueId],a=("number"==typeof s?r[s]:i).createInstance(t.name);u(t,a)}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}`);u(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=r[n[e.uniqueId]];if(!t||t.isAnInstance)continue;if(t.skeleton=i,-1!==a.indexOf(i))continue;a.push(i);for(const e of i.bones)e._linkedTransformNode&&(e._linkedTransformNode=r[n[e._linkedTransformNode.uniqueId]])}s.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=>r[n[e.uniqueId]]||e));s.animationGroups.push(i)})),s}addAllToScene(){if(!this._wasAddedToScene){this._isValidHierarchy()||Yt.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()||Yt.Warn("SceneSerializer.removeAllFromScene: The Asset Container hierarchy is not valid."),this._wasAddedToScene=!1,this.removeFromScene(null),this.environmentTexture===this.scene.environmentTexture&&(this.scene.environmentTexture=null);for(const e of this.scene._serializableComponents)e.removeFromContainer(this)}removeFromScene(e=null){this.cameras.forEach((t=>{e&&!e(t)||this.scene.removeCamera(t)})),this.lights.forEach((t=>{e&&!e(t)||this.scene.removeLight(t)})),this.meshes.forEach((t=>{e&&!e(t)||this.scene.removeMesh(t,!0)})),this.skeletons.forEach((t=>{e&&!e(t)||this.scene.removeSkeleton(t)})),this.animations.forEach((t=>{e&&!e(t)||this.scene.removeAnimation(t)})),this.animationGroups.forEach((t=>{e&&!e(t)||this.scene.removeAnimationGroup(t)})),this.multiMaterials.forEach((t=>{e&&!e(t)||this.scene.removeMultiMaterial(t)})),this.materials.forEach((t=>{e&&!e(t)||this.scene.removeMaterial(t)})),this.morphTargetManagers.forEach((t=>{e&&!e(t)||this.scene.removeMorphTargetManager(t)})),this.geometries.forEach((t=>{e&&!e(t)||this.scene.removeGeometry(t)})),this.transformNodes.forEach((t=>{e&&!e(t)||this.scene.removeTransformNode(t)})),this.actionManagers.forEach((t=>{e&&!e(t)||this.scene.removeActionManager(t)})),this.textures.forEach((t=>{e&&!e(t)||this.scene.removeTexture(t)})),this.reflectionProbes.forEach((t=>{e&&!e(t)||this.scene.removeReflectionProbe(t)}))}dispose(){this.cameras.slice(0).forEach((e=>{e.dispose()})),this.cameras.length=0,this.lights.slice(0).forEach((e=>{e.dispose()})),this.lights.length=0,this.meshes.slice(0).forEach((e=>{e.dispose()})),this.meshes.length=0,this.skeletons.slice(0).forEach((e=>{e.dispose()})),this.skeletons.length=0,this.animationGroups.slice(0).forEach((e=>{e.dispose()})),this.animationGroups.length=0,this.multiMaterials.slice(0).forEach((e=>{e.dispose()})),this.multiMaterials.length=0,this.materials.slice(0).forEach((e=>{e.dispose()})),this.materials.length=0,this.geometries.slice(0).forEach((e=>{e.dispose()})),this.geometries.length=0,this.transformNodes.slice(0).forEach((e=>{e.dispose()})),this.transformNodes.length=0,this.actionManagers.slice(0).forEach((e=>{e.dispose()})),this.actionManagers.length=0,this.textures.slice(0).forEach((e=>{e.dispose()})),this.textures.length=0,this.reflectionProbes.slice(0).forEach((e=>{e.dispose()})),this.reflectionProbes.length=0,this.morphTargetManagers.slice(0).forEach((e=>{e.dispose()})),this.morphTargetManagers.length=0,this.environmentTexture&&(this.environmentTexture.dispose(),this.environmentTexture=null);for(const e of this.scene._serializableComponents)e.removeFromContainer(this,!0);this._onContextRestoredObserver&&(this.scene.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)}_moveAssets(e,t,i){if(e&&t)for(const n of e){let e=!0;if(i)for(const t of i)if(n===t){e=!1;break}e&&(t.push(n),n._parentContainer=this)}}moveAllFromScene(e){this._wasAddedToScene=!1,void 0===e&&(e=new Ua);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 ln("assetContainerRootMesh",this.scene);return this.meshes.forEach((t=>{t.parent||e.addChild(t)})),this.meshes.unshift(e),e}mergeAnimationsTo(e=y.LastCreatedScene,t,i=null){if(!e)return de.Error("No scene available to merge animations to"),[];const n=i||(t=>{let i=null;const n=t.animations.length?t.animations[0].targetProperty:"",r=t.name.split(".").join("").split("_primitive")[0];switch(n){case"position":case"rotationQuaternion":i=e.getTransformNodeByName(t.name)||e.getTransformNodeByName(r);break;case"influence":i=e.getMorphTargetByName(t.name)||e.getMorphTargetByName(r);break;default:i=e.getNodeByName(t.name)||e.getNodeByName(r)}return i});this.getNodes().forEach((e=>{const t=n(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 r=[];return this.animationGroups.slice().forEach((e=>{r.push(e.clone(e.name,n)),e.animatables.forEach((e=>{e.stop()}))})),t.forEach((t=>{const i=n(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))})),r}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 ln?(e.geometry&&-1===this.geometries.indexOf(e.geometry)&&this.geometries.push(e.geometry),this.meshes.push(e)):e instanceof Si?this.transformNodes.push(e):e instanceof Xn?this.lights.push(e):e instanceof ii&&this.cameras.push(e),e instanceof Vi){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 n of e.getChildren())i.has(n)||t.push(n);i.add(e)}this.populateRootNodes()}}class Va{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(e=>{if("undefined"!=typeof TextDecoder)return(new TextDecoder).decode(e);let t="";for(let i=0;i<e.byteLength;i++)t+=String.fromCharCode(e[i]);return t})(this.readUint8Array(e))}skipBytes(e){this._dataByteOffset+=e,this.byteOffset+=e}}function ka(e,t,i,n){const r={externalResourceFunction:n};return i&&(r.uri="file:"===t?i:t+i),ArrayBuffer.isView(e)?GLTFValidator.validateBytes(e,r):GLTFValidator.validateString(e,r)}function Xa(){const e=[];onmessage=t=>{const i=t.data;switch(i.id){case"init":importScripts(i.url);break;case"validate":ka(i.data,i.rootUrl,i.fileName,(t=>new Promise(((i,n)=>{const r=e.length;e.push({resolve:i,reject:n}),postMessage({id:"getExternalResource",index:r,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)}}}class Ha{static ValidateAsync(e,t,i,n){return"function"==typeof Worker?new Promise(((r,s)=>{const a=`${ka}(${Xa})()`,o=URL.createObjectURL(new Blob([a],{type:"application/javascript"})),l=new Worker(o),c=e=>{l.removeEventListener("error",c),l.removeEventListener("message",h),s(e)},h=e=>{const t=e.data;switch(t.id){case"getExternalResource":n(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",c),l.removeEventListener("message",h),r(t.value),l.terminate();break;case"validate.reject":l.removeEventListener("error",c),l.removeEventListener("message",h),s(t.reason),l.terminate()}};if(l.addEventListener("error",c),l.addEventListener("message",h),l.postMessage({id:"init",url:Yt.GetBabylonScriptURL(this.Configuration.url)}),ArrayBuffer.isView(e)){const n=e.slice();l.postMessage({id:"validate",data:n,rootUrl:t,fileName:i},[n.buffer])}else l.postMessage({id:"validate",data:e,rootUrl:t,fileName:i})})):(this._LoadScriptPromise||(this._LoadScriptPromise=Yt.LoadBabylonScriptAsync(this.Configuration.url)),this._LoadScriptPromise.then((()=>ka(e,t,i,n))))}}Ha.Configuration={url:`${Yt._DefaultCdnUrl}/gltf_validator.js`};const Wa="gltf";function za(e,t,i){try{return Promise.resolve(new Uint8Array(e,t,i))}catch(e){return Promise.reject(e)}}var Ya,Ka,qa;!function(e){e[e.AUTO=0]="AUTO",e[e.FORCE_RIGHT_HANDED=1]="FORCE_RIGHT_HANDED"}(Ya||(Ya={})),function(e){e[e.NONE=0]="NONE",e[e.FIRST=1]="FIRST",e[e.ALL=2]="ALL"}(Ka||(Ka={})),function(e){e[e.LOADING=0]="LOADING",e[e.READY=1]="READY",e[e.COMPLETE=2]="COMPLETE"}(qa||(qa={}));class ja{constructor(){this.coordinateSystemMode=Ya.AUTO,this.animationStartMode=Ka.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.preprocessUrlAsync=e=>Promise.resolve(e),this.extensionOptions={}}copyFrom(e){if(e){const t=t=>{const i=t;this[i]=e[i]??this[i]};for(const e in this)t(e);for(const e of["onParsed","onMeshLoaded","onSkinLoaded","onTextureLoaded","onMaterialLoaded","onCameraLoaded"])t(e)}}}class Qa extends ja{constructor(e){super(),this.onParsedObservable=new g,this.onMeshLoadedObservable=new g,this.onSkinLoadedObservable=new g,this.onTextureLoadedObservable=new g,this.onMaterialLoadedObservable=new g,this.onCameraLoadedObservable=new g,this.onCompleteObservable=new g,this.onErrorObservable=new g,this.onDisposeObservable=new g,this.onExtensionLoadedObservable=new g,this.validate=!1,this.onValidatedObservable=new g,this._loader=null,this._state=null,this._requests=new Array,this.name=Wa,this.extensions={".gltf":{isBinary:!1},".glb":{isBinary:!0}},this.onLoaderStateChangedObservable=new g,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,n,r,s,a,o){if(ArrayBuffer.isView(t))return this._loadBinary(e,t,i,n,a,o),null;this._progressCallback=r;const l=t.name||Yt.GetFilename(t);if(s){if(this.useRangeRequests){this.validate&&de.Warn("glTF validation is not supported when range requests are enabled");const i={abort:()=>{},onCompleteObservable:new g},r={readAsync:(i,n)=>new Promise(((r,s)=>{this._loadFile(e,t,(e=>{r(new Uint8Array(e))}),!0,(e=>{s(e)}),(e=>{e.setRequestHeader("Range",`bytes=${i}-${i+n-1}`)}))})),byteLength:0};return this._unpackBinaryAsync(new Va(r)).then((e=>{i.onCompleteObservable.notifyObservers(i),n(e)}),a?e=>a(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 Va({readAsync:(e,i)=>za(t,e,i),byteLength:t.byteLength})).then((e=>{n(e)}),a?e=>a(void 0,e):void 0)}),!0,a)}return this._loadFile(e,t,(t=>{try{this._validate(e,t,i,l),n({json:this._parseJson(t)})}catch{a&&a()}}),!1,a)}_loadBinary(e,t,i,n,r,s){this._validate(e,new Uint8Array(t.buffer,t.byteOffset,t.byteLength),i,s),this._unpackBinaryAsync(new Va({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=>{n(e)}),r?e=>r(void 0,e):void 0)}importMeshAsync(e,t,i,n,r,s){return Promise.resolve().then((()=>(this.onParsedObservable.notifyObservers(i),this.onParsedObservable.clear(),this._log(`Loading ${s||""}`),this._loader=this._getLoader(i),this._loader.importMeshAsync(e,t,null,i,n,r,s))))}loadAsync(e,t,i,n,r){return Promise.resolve().then((()=>(this.onParsedObservable.notifyObservers(t),this.onParsedObservable.clear(),this._log(`Loading ${r||""}`),this._loader=this._getLoader(t),this._loader.loadAsync(e,t,i,n,r))))}loadAssetContainerAsync(e,t,i,n,r){return Promise.resolve().then((()=>{this.onParsedObservable.notifyObservers(t),this.onParsedObservable.clear(),this._log(`Loading ${r||""}`),this._loader=this._getLoader(t);const s=new Ga(e),a=[];this.onMaterialLoadedObservable.add((e=>{a.push(e)}));const o=[];this.onTextureLoadedObservable.add((e=>{o.push(e)}));const l=[];this.onCameraLoadedObservable.add((e=>{l.push(e)}));const c=[];return this.onMeshLoadedObservable.add((e=>{e.morphTargetManager&&c.push(e.morphTargetManager)})),this._loader.importMeshAsync(null,e,s,t,i,n,r).then((e=>(Array.prototype.push.apply(s.geometries,e.geometries),Array.prototype.push.apply(s.meshes,e.meshes),Array.prototype.push.apply(s.particleSystems,e.particleSystems),Array.prototype.push.apply(s.skeletons,e.skeletons),Array.prototype.push.apply(s.animationGroups,e.animationGroups),Array.prototype.push.apply(s.materials,a),Array.prototype.push.apply(s.textures,o),Array.prototype.push.apply(s.lights,e.lights),Array.prototype.push.apply(s.transformNodes,e.transformNodes),Array.prototype.push.apply(s.cameras,l),Array.prototype.push.apply(s.morphTargetManagers,c),s)))}))}canDirectLoad(e){return-1!==e.indexOf("asset")&&-1!==e.indexOf("version")||e.startsWith("data:base64,"+Qa._MagicBase64Encoded)||e.startsWith("data:;base64,"+Qa._MagicBase64Encoded)||e.startsWith("data:application/octet-stream;base64,"+Qa._MagicBase64Encoded)||e.startsWith("data:model/gltf-binary;base64,"+Qa._MagicBase64Encoded)}directLoad(e,t){if(t.startsWith("base64,"+Qa._MagicBase64Encoded)||t.startsWith(";base64,"+Qa._MagicBase64Encoded)||t.startsWith("application/octet-stream;base64,"+Qa._MagicBase64Encoded)||t.startsWith("model/gltf-binary;base64,"+Qa._MagicBase64Encoded)){const i=Ft(t);return this._validate(e,new Uint8Array(i,0,i.byteLength)),this._unpackBinaryAsync(new Va({readAsync:(e,t)=>za(i,e,t),byteLength:i.byteLength}))}return this._validate(e,t),Promise.resolve({json:this._parseJson(t)})}createPlugin(e){return new Qa(e[Wa])}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(qa[this._state]))}_loadFile(e,t,i,n,r,s){const a=e._loadFile(t,i,(e=>{this._onProgress(e,a)}),!0,n,r,s);return a.onCompleteObservable.add((()=>{a._lengthComputable=!0,a._total=a._loaded})),this._requests.push(a),a}_onProgress(e,t){if(!this._progressCallback)return;t._lengthComputable=e.lengthComputable,t._loaded=e.loaded,t._total=e.total;let i=!0,n=0,r=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,n+=e._loaded,r+=e._total}this._progressCallback({lengthComputable:i,loaded:n,total:i?r:0})}_validate(e,t,i="",n=""){this.validate&&(this._startPerformanceCounter("Validate JSON"),Ha.ValidateAsync(t,i,n,(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"),Yt.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=Qa._parseVersion(t.version);if(!i)throw new Error("Invalid version: "+t.version);if(void 0!==t.minVersion){const e=Qa._parseVersion(t.minVersion);if(!e)throw new Error("Invalid minimum version: "+t.minVersion);if(Qa._compareVersion(e,{major:2,minor:0})>0)throw new Error("Incompatible minimum version: "+t.minVersion)}const n={1:Qa._CreateGLTF1Loader,2:Qa._CreateGLTF2Loader}[i.major];if(!n)throw new Error("Unsupported version: "+t.version);return n(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 Te("Unexpected magic: "+t,Ee.GLTFLoaderUnexpectedMagicError);const i=e.readUint32();this.loggingEnabled&&this._log(`Binary version: ${i}`);const n=e.readUint32();let r;switch(this.useRangeRequests||n===e.buffer.byteLength||de.Warn(`Length in header does not match actual data length: ${n} != ${e.buffer.byteLength}`),i){case 1:r=this._unpackBinaryV1Async(e,n);break;case 2:r=this._unpackBinaryV2Async(e,n);break;default:throw new Error("Unsupported version: "+i)}return this._endPerformanceCounter("Unpack Binary"),r}))}_unpackBinaryV1Async(e,t){const i=e.readUint32(),n=e.readUint32();if(0!==n)throw new Error(`Unexpected content format: ${n}`);const r=t-e.byteOffset,s={json:this._parseJson(e.readString(i)),bin:null};if(0!==r){const t=e.byteOffset;s.bin={readAsync:(i,n)=>e.buffer.readAsync(t+i,n),byteLength:r}}return Promise.resolve(s)}_unpackBinaryV2Async(e,t){const i=1313821514,n=5130562,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},a=()=>{const r=e.readUint32();switch(e.readUint32()){case i:throw new Error("Unexpected JSON chunk");case n:{const t=e.byteOffset;s.bin={readAsync:(i,n)=>e.buffer.readAsync(t+i,n),byteLength:r},e.skipBytes(r);break}default:e.skipBytes(r)}return e.byteOffset!==t?e.loadAsync(8).then(a):Promise.resolve(s)};return a()}))}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.major<t.major?-1:e.minor>t.minor?1:e.minor<t.minor?-1:0}_logOpen(e){this._log(e),this._logIndentLevel++}_logClose(){--this._logIndentLevel}_logEnabled(e){const t=Qa._logSpaces.substr(0,2*this._logIndentLevel);de.Log(`${t}${e}`)}_logDisabled(e){}_startPerformanceCounterEnabled(e){Yt.StartPerformanceCounter(e)}_startPerformanceCounterDisabled(e){}_endPerformanceCounterEnabled(e){Yt.EndPerformanceCounter(e)}_endPerformanceCounterDisabled(e){}}function Za(e,t,i,n){return B.FromArray(t,i).scaleInPlace(n)}Qa.IncrementalLoading=!0,Qa.HomogeneousCoordinates=!1,Qa._MagicBase64Encoded="Z2xURg",Qa._logSpaces=" ",function(e){if("string"==typeof e.extensions){const t=e.extensions;Ir[t.toLowerCase()]={plugin:e,isBinary:!1}}else{const t=e.extensions;Object.keys(t).forEach((i=>{Ir[i.toLowerCase()]={plugin:e,isBinary:t[i].isBinary}}))}}(new Qa);class Ja{constructor(e,t,i,n){this.type=e,this.name=t,this.getValue=i,this.getStride=n}_buildAnimation(e,t,i){const n=new Cn(e,this.name,t,this.type);return n.setKeys(i),n}}class $a extends Ja{buildAnimations(e,t,i,n,r){r(e._babylonTransformNode,this._buildAnimation(t,i,n))}}const eo={translation:[new $a(Cn.ANIMATIONTYPE_VECTOR3,"position",Za,(()=>3))],rotation:[new $a(Cn.ANIMATIONTYPE_QUATERNION,"rotationQuaternion",(function(e,t,i,n){return V.FromArray(t,i).scaleInPlace(n)}),(()=>4))],scale:[new $a(Cn.ANIMATIONTYPE_VECTOR3,"scaling",Za,(()=>3))],weights:[new class extends Ja{buildAnimations(e,t,i,n,r){if(e._numMorphTargets)for(let s=0;s<e._numMorphTargets;s++){const a=new Cn(`${t}_${s}`,this.name,i,this.type);if(a.setKeys(n.map((e=>({frame:e.frame,inTangent:e.inTangent?e.inTangent[s]:void 0,value:e.value[s],outTangent:e.outTangent?e.outTangent[s]:void 0,interpolation:e.interpolation})))),e._primitiveBabylonMeshes)for(const t of e._primitiveBabylonMeshes)if(t.morphTargetManager){const e=t.morphTargetManager.getTarget(s),i=a.clone();e.animations.push(i),r(e,i)}}}}(Cn.ANIMATIONTYPE_FLOAT,"influence",(function(e,t,i,n){const r=new Array(e._numMorphTargets);for(let e=0;e<r.length;e++)r[e]=t[i++]*n;return r}),(e=>e._numMorphTargets))]};function to(...e){const t=e=>e&&"object"==typeof e;return e.reduce(((e,i)=>(Object.keys(i).forEach((n=>{const r=e[n],s=i[n];Array.isArray(r)&&Array.isArray(s)?e[n]=r.concat(...s):t(r)&&t(s)?e[n]=to(r,s):e[n]=s})),e)),{})}class io{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;t<e.length;t++)e[t].index=t}}class no{static RegisterExtension(e,t){no.UnregisterExtension(e)&&de.Warn(`Extension with the name '${e}' already exists`),no._RegisteredExtensions[e]={factory:t}}static UnregisterExtension(e){return!!no._RegisteredExtensions[e]&&(delete no._RegisteredExtensions[e],!0)}get gltf(){if(!this._gltf)throw new Error("glTF JSON is not available");return this._gltf}get bin(){return this._bin}get parent(){return this._parent}get babylonScene(){if(!this._babylonScene)throw new Error("Scene is not available");return this._babylonScene}get rootBabylonMesh(){return this._rootBabylonMesh}get rootUrl(){return this._rootUrl}constructor(e){this._completePromises=new Array,this._assetContainer=null,this._babylonLights=[],this._disableInstancedMesh=0,this._allMaterialsDirtyRequired=!1,this._extensions=new Array,this._disposed=!1,this._rootUrl=null,this._fileName=null,this._uniqueRootUrl=null,this._bin=null,this._rootBabylonMesh=null,this._defaultBabylonMaterialData={},this._postSceneLoadActions=new Array,this._parent=e}dispose(){this._disposed||(this._disposed=!0,this._completePromises.length=0,this._extensions.forEach((e=>e.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,n,r,s,a=""){return Promise.resolve().then((()=>{this._babylonScene=t,this._assetContainer=i,this._loadData(n);let s=null;if(e){const t={};if(this._gltf.nodes)for(const e of this._gltf.nodes)e.name&&(t[e.name]=e.index);s=(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(r,a,s,(()=>({meshes:this._getMeshes(),particleSystems:[],skeletons:this._getSkeletons(),animationGroups:this._getAnimationGroups(),lights:this._babylonLights,transformNodes:this._getTransformNodes(),geometries:this._getGeometries(),spriteManagers:[]})))}))}loadAsync(e,t,i,n,r=""){return Promise.resolve().then((()=>(this._babylonScene=e,this._loadData(t),this._loadAsync(i,r,null,(()=>{})))))}_loadAsync(e,t,i,n){return Promise.resolve().then((()=>{this._rootUrl=e,this._uniqueRootUrl=!e.startsWith("file:")&&t?e:`${e}${Date.now()}/`,this._fileName=t,this._allMaterialsDirtyRequired=!1,this._loadExtensions(),this._checkExtensions();const r=`${qa[qa.LOADING]} => ${qa[qa.READY]}`,s=`${qa[qa.LOADING]} => ${qa[qa.COMPLETE]}`;this._parent._startPerformanceCounter(r),this._parent._startPerformanceCounter(s),this._parent._setState(qa.LOADING),this._extensionsOnLoading();const a=new Array,o=this._babylonScene.blockMaterialDirtyMechanism;if(this._babylonScene.blockMaterialDirtyMechanism=!0,!this.parent.loadOnlyMaterials)if(i)a.push(this.loadSceneAsync("/nodes",{nodes:i,index:-1}));else if(null!=this._gltf.scene||this._gltf.scenes&&this._gltf.scenes[0]){const e=io.Get("/scene",this._gltf.scenes,this._gltf.scene||0);a.push(this.loadSceneAsync(`/scenes/${e.index}`,e))}if(!this.parent.skipMaterials&&this.parent.loadAllMaterials&&this._gltf.materials)for(let e=0;e<this._gltf.materials.length;++e){const t=this._gltf.materials[e],i="/materials/"+e,n=Ji.TriangleFillMode;a.push(this._loadMaterialAsync(i,t,null,n,(()=>{})))}this._allMaterialsDirtyRequired?this._babylonScene.blockMaterialDirtyMechanism=o:this._babylonScene._forceBlockMaterialDirtyMechanism(o),this._parent.compileMaterials&&a.push(this._compileMaterialsAsync()),this._parent.compileShadowGenerators&&a.push(this._compileShadowGeneratorsAsync());return Promise.all(a).then((()=>(this._rootBabylonMesh&&this._rootBabylonMesh!==this._parent.customRootNode&&this._rootBabylonMesh.setEnabled(!0),this._extensionsOnReady(),this._parent._setState(qa.READY),this._startAnimations(),n()))).then((e=>(this._parent._endPerformanceCounter(r),Yt.SetImmediate((()=>{this._disposed||Promise.all(this._completePromises).then((()=>{this._parent._endPerformanceCounter(s),this._parent._setState(qa.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.byteLength<e.bin.byteLength-3||i.byteLength>e.bin.byteLength)&&de.Warn(`Binary buffer length (${i.byteLength}) from JSON does not match chunk length (${e.bin.byteLength})`),this._bin=e.bin}else de.Warn("Unexpected BIN chunk")}}_setupData(){if(io.Assign(this._gltf.accessors),io.Assign(this._gltf.animations),io.Assign(this._gltf.buffers),io.Assign(this._gltf.bufferViews),io.Assign(this._gltf.cameras),io.Assign(this._gltf.images),io.Assign(this._gltf.materials),io.Assign(this._gltf.meshes),io.Assign(this._gltf.nodes),io.Assign(this._gltf.samplers),io.Assign(this._gltf.scenes),io.Assign(this._gltf.skins),io.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 n=e[i.index];i.parent=void 0===n?t:this._gltf.nodes[n]}}}_loadExtensions(){for(const e in no._RegisteredExtensions)if(!1===this.parent.extensionOptions[e]?.enabled)this.isExtensionUsed(e)&&de.Warn(`Extension ${e} is used but has been explicitly disabled.`);else{const t=no._RegisteredExtensions[e].factory(this);t.name!==e&&de.Warn(`The name of the glTF loader extension instance does not match the registered name: ${t.name} !== ${e}`),this._extensions.push(t),this._parent.onExtensionLoadedObservable.notifyObservers(t)}this._extensions.sort(((e,t)=>(e.order||Number.MAX_VALUE)-(t.order||Number.MAX_VALUE))),this._parent.onExtensionLoadedObservable.clear()}_checkExtensions(){if(this._gltf.extensionsRequired)for(const e of this._gltf.extensionsRequired){if(!this._extensions.some((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 ln("__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 Ya.AUTO:this._babylonScene.useRightHandedSystem||(t.rotation=[0,1,0,0],t.scale=[1,1,-1],no._LoadTransform(t,this._rootBabylonMesh));break;case Ya.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 n=new Array;if(this.logOpen(`${e} ${t.name||""}`),t.nodes)for(const i of t.nodes){const t=io.Get(`${e}/nodes/${i}`,this._gltf.nodes,i);n.push(this.loadNodeAsync(`/nodes/${t.index}`,t,(e=>{e.parent=this._rootBabylonMesh})))}for(const e of this._postSceneLoadActions)e();return n.push(this._loadAnimationsAsync()),this.logClose(),Promise.all(n).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 Vi&&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 Ka.NONE:break;case Ka.FIRST:{const e=this._getAnimationGroups();0!==e.length&&e[0].start(!0);break}case Ka.ALL:{const e=this._getAnimationGroups();for(const t of e)t.start(!0);break}default:return void de.Error(`Invalid animation start mode (${this._parent.animationStartMode})`)}}loadNodeAsync(e,t,i=()=>{}){const n=this._extensionsLoadNodeAsync(e,t,i);if(n)return n;if(t._babylonTransformNode)throw new Error(`${e}: Invalid recursive node hierarchy`);const r=new Array;this.logOpen(`${e} ${t.name||""}`);const s=n=>{if(no.AddPointerMetadata(n,e),no._LoadTransform(t,n),null!=t.camera){const i=io.Get(`${e}/camera`,this._gltf.cameras,t.camera);r.push(this.loadCameraAsync(`/cameras/${i.index}`,i,(e=>{e.parent=n})))}if(t.children)for(const i of t.children){const t=io.Get(`${e}/children/${i}`,this._gltf.nodes,i);r.push(this.loadNodeAsync(`/nodes/${t.index}`,t,(e=>{e.parent=n})))}i(n)},a=null!=t.mesh,o=this._parent.loadSkins&&null!=t.skin;if(!a||o){const e=t.name||`node${t.index}`;this._babylonScene._blockEntityCollection=!!this._assetContainer;const i=new Si(e,this._babylonScene);i._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,null==t.mesh?t._babylonTransformNode=i:t._babylonTransformNodeForSkin=i,s(i)}if(a)if(o){const i=io.Get(`${e}/mesh`,this._gltf.meshes,t.mesh);r.push(this._loadMeshAsync(`/meshes/${i.index}`,t,i,(i=>{const n=t._babylonTransformNodeForSkin;i.metadata=to(n.metadata,i.metadata||{});const s=io.Get(`${e}/skin`,this._gltf.skins,t.skin);r.push(this._loadSkinAsync(`/skins/${s.index}`,t,s,(e=>{this._forEachPrimitive(t,(t=>{t.skeleton=e})),this._postSceneLoadActions.push((()=>{if(null!=s.skeleton){const e=io.Get(`/skins/${s.index}/skeleton`,this._gltf.nodes,s.skeleton).parent;t.index===e.index?i.parent=n.parent:i.parent=e._babylonTransformNode}else i.parent=this._rootBabylonMesh;this._parent.onSkinLoadedObservable.notifyObservers({node:n,skinnedNode:i})}))})))})))}else{const i=io.Get(`${e}/mesh`,this._gltf.meshes,t.mesh);r.push(this._loadMeshAsync(`/meshes/${i.index}`,t,i,s))}return this.logClose(),Promise.all(r).then((()=>(this._forEachPrimitive(t,(e=>{e.geometry&&e.geometry.useBoundingInfoFromGeometry?e._updateBoundingInfo():e.refreshBoundingInfo(!0,!0)})),t._babylonTransformNode)))}_loadMeshAsync(e,t,i,n){const r=i.primitives;if(!r||!r.length)throw new Error(`${e}: Primitives are missing`);null==r[0].index&&io.Assign(r);const s=new Array;this.logOpen(`${e} ${i.name||""}`);const a=t.name||`node${t.index}`;if(1===r.length){const n=i.primitives[0];s.push(this._loadMeshPrimitiveAsync(`${e}/primitives/${n.index}`,a,t,i,n,(e=>{t._babylonTransformNode=e,t._primitiveBabylonMeshes=[e]})))}else{this._babylonScene._blockEntityCollection=!!this._assetContainer,t._babylonTransformNode=new Si(a,this._babylonScene),t._babylonTransformNode._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,t._primitiveBabylonMeshes=[];for(const n of r)s.push(this._loadMeshPrimitiveAsync(`${e}/primitives/${n.index}`,`${a}_primitive${n.index}`,t,i,n,(e=>{e.parent=t._babylonTransformNode,t._primitiveBabylonMeshes.push(e)})))}return n(t._babylonTransformNode),this.logClose(),Promise.all(s).then((()=>t._babylonTransformNode))}_loadMeshPrimitiveAsync(e,t,i,n,r,s){const a=this._extensionsLoadMeshPrimitiveAsync(e,t,i,n,r,s);if(a)return a;this.logOpen(`${e}`);const o=0===this._disableInstancedMesh&&this._parent.createInstances&&null==i.skin&&!n.primitives[0].targets;let l,c;if(o&&r._instanceData)this._babylonScene._blockEntityCollection=!!this._assetContainer,l=r._instanceData.babylonSourceMesh.createInstance(t),l._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,c=r._instanceData.promise;else{const s=new Array;this._babylonScene._blockEntityCollection=!!this._assetContainer;const a=new ln(t,this._babylonScene);a._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,a.sideOrientation=this._babylonScene.useRightHandedSystem?Ji.CounterClockWiseSideOrientation:Ji.ClockWiseSideOrientation,this._createMorphTargets(e,i,n,r,a),s.push(this._loadVertexDataAsync(e,r,a).then((t=>this._loadMorphTargetsAsync(e,r,a,t).then((()=>{this._disposed||(this._babylonScene._blockEntityCollection=!!this._assetContainer,t.applyToMesh(a),t._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1)})))));const h=no._GetDrawMode(e,r.mode);if(null==r.material){let e=this._defaultBabylonMaterialData[h];e||(e=this._createDefaultMaterial("__GLTFLoader._default",h),this._parent.onMaterialLoadedObservable.notifyObservers(e),this._defaultBabylonMaterialData[h]=e),a.material=e}else if(!this.parent.skipMaterials){const t=io.Get(`${e}/material`,this._gltf.materials,r.material);s.push(this._loadMaterialAsync(`/materials/${t.index}`,t,a,h,(e=>{a.material=e})))}c=Promise.all(s),o&&(r._instanceData={babylonSourceMesh:a,promise:c}),l=a}return no.AddPointerMetadata(l,e),this._parent.onMeshLoadedObservable.notifyObservers(l),s(l),this.logClose(),c.then((()=>l))}_loadVertexDataAsync(e,t,i){const n=this._extensionsLoadVertexDataAsync(e,t,i);if(n)return n;const r=t.attributes;if(!r)throw new Error(`${e}: Attributes are missing`);const s=new Array,a=new vi(i.name,this._babylonScene);if(null==t.indices)i.isUnIndexed=!0;else{const i=io.Get(`${e}/indices`,this._gltf.accessors,t.indices);s.push(this._loadIndicesAccessorAsync(`/accessors/${i.index}`,i).then((e=>{a.setIndices(e)})))}const o=(t,n,o)=>{if(null==r[t])return;i._delayInfo=i._delayInfo||[],-1===i._delayInfo.indexOf(n)&&i._delayInfo.push(n);const l=io.Get(`${e}/attributes/${t}`,this._gltf.accessors,r[t]);s.push(this._loadVertexAccessorAsync(`/accessors/${l.index}`,l,n).then((e=>{if(e.getKind()===si.PositionKind&&!this.parent.alwaysComputeBoundingBox&&!i.skeleton&&l.min&&l.max){const e=H.Vector3[0].copyFromFloats(...l.min),t=H.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 n=1/i;e.scaleInPlace(n),t.scaleInPlace(n)}a._boundingInfo=new fi(e,t),a.useBoundingInfoFromGeometry=!0}a.setVerticesBuffer(e,l.count)}))),n==si.MatricesIndicesExtraKind&&(i.numBoneInfluencers=8),o&&o(l)};return o("POSITION",si.PositionKind),o("NORMAL",si.NormalKind),o("TANGENT",si.TangentKind),o("TEXCOORD_0",si.UVKind),o("TEXCOORD_1",si.UV2Kind),o("TEXCOORD_2",si.UV3Kind),o("TEXCOORD_3",si.UV4Kind),o("TEXCOORD_4",si.UV5Kind),o("TEXCOORD_5",si.UV6Kind),o("JOINTS_0",si.MatricesIndicesKind),o("WEIGHTS_0",si.MatricesWeightsKind),o("JOINTS_1",si.MatricesIndicesExtraKind),o("WEIGHTS_1",si.MatricesWeightsExtraKind),o("COLOR_0",si.ColorKind,(e=>{"VEC4"===e.type&&(i.hasVertexAlpha=!0)})),Promise.all(s).then((()=>a))}_createMorphTargets(e,t,i,n,r){if(!n.targets||!this._parent.loadMorphTargets)return;if(null==t._numMorphTargets)t._numMorphTargets=n.targets.length;else if(n.targets.length!==t._numMorphTargets)throw new Error(`${e}: Primitives do not have the same number of targets`);const s=i.extras?i.extras.targetNames:null;this._babylonScene._blockEntityCollection=!!this._assetContainer,r.morphTargetManager=new Fa(this._babylonScene),r.morphTargetManager._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,r.morphTargetManager.areUpdatesFrozen=!0;for(let e=0;e<n.targets.length;e++){const n=t.weights?t.weights[e]:i.weights?i.weights[e]:0,a=s?s[e]:`morphTarget${e}`;r.morphTargetManager.addTarget(new Pa(a,n,r.getScene()))}}_loadMorphTargetsAsync(e,t,i,n){if(!t.targets||!this._parent.loadMorphTargets)return Promise.resolve();const r=new Array,s=i.morphTargetManager;for(let i=0;i<s.numTargets;i++){const a=s.getTarget(i);r.push(this._loadMorphTargetVertexDataAsync(`${e}/targets/${i}`,n,t.targets[i],a))}return Promise.all(r).then((()=>{s.areUpdatesFrozen=!1}))}_loadMorphTargetVertexDataAsync(e,t,i,n){const r=new Array,s=(n,s,a)=>{if(null==i[n])return;const o=t.getVertexBuffer(s);if(!o)return;const l=io.Get(`${e}/${n}`,this._gltf.accessors,i[n]);r.push(this._loadFloatAccessorAsync(`/accessors/${l.index}`,l).then((e=>{a(o,e)})))};return s("POSITION",si.PositionKind,((e,t)=>{const i=new Float32Array(t.length);e.forEach(t.length,((e,n)=>{i[n]=t[n]+e})),n.setPositions(i)})),s("NORMAL",si.NormalKind,((e,t)=>{const i=new Float32Array(t.length);e.forEach(i.length,((e,n)=>{i[n]=t[n]+e})),n.setNormals(i)})),s("TANGENT",si.TangentKind,((e,t)=>{const i=new Float32Array(t.length/3*4);let r=0;e.forEach(t.length/3*4,((e,n)=>{(n+1)%4!=0&&(i[r]=t[r]+e,r++)})),n.setTangents(i)})),Promise.all(r).then((()=>{}))}static _LoadTransform(e,t){if(null!=e.skin)return;let i=B.Zero(),n=V.Identity(),r=B.One();if(e.matrix){k.FromArray(e.matrix).decompose(r,n,i)}else e.translation&&(i=B.FromArray(e.translation)),e.rotation&&(n=V.FromArray(e.rotation)),e.scale&&(r=B.FromArray(e.scale));t.position=i,t.rotationQuaternion=n,t.scaling=r}_loadSkinAsync(e,t,i,n){if(!this._parent.loadSkins)return Promise.resolve();const r=this._extensionsLoadSkinAsync(e,t,i);if(r)return r;if(i._data)return n(i._data.babylonSkeleton),i._data.promise;const s=`skeleton${i.index}`;this._babylonScene._blockEntityCollection=!!this._assetContainer;const a=new Na(i.name||s,s,this._babylonScene);a._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,this._loadBones(e,i,a);const o=this._loadSkinInverseBindMatricesDataAsync(e,i).then((e=>{this._updateBoneMatrices(a,e)}));return i._data={babylonSkeleton:a,promise:o},n(a),o}_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 n=(e,t)=>{for(;t.parent;t=t.parent)if(t.parent===e)return!0;return!1},r=io.Get(`${e}/skeleton`,this._gltf.nodes,t.skeleton);r===i||n(r,i)||(de.Warn(`${e}/skeleton: Overriding with nearest common ancestor as skeleton node is not a common root`),t.skeleton=i.index)}else de.Warn(`${e}: Failed to find common root`)}const n={};for(const r of t.joints){const s=io.Get(`${e}/joints/${r}`,this._gltf.nodes,r);this._loadBone(s,t,i,n)}}_findSkeletonRootNode(e,t){if(0===t.length)return null;const i={};for(const n of t){const t=[];let r=io.Get(`${e}/${n}`,this._gltf.nodes,n);for(;-1!==r.index;)t.unshift(r),r=r.parent;i[n]=t}let n=null;for(let e=0;;++e){let r=i[t[0]];if(e>=r.length)return n;const s=r[e];for(let a=1;a<t.length;++a)if(r=i[t[a]],e>=r.length||s!==r[e])return n;n=s}}_loadBone(e,t,i,n){e._isJoint=!0;let r=n[e.index];if(r)return r;let s=null;e.index!==t.skeleton&&(e.parent&&-1!==e.parent.index?s=this._loadBone(e.parent,t,i,n):void 0!==t.skeleton&&de.Warn(`/skins/${t.index}/skeleton: Skeleton node is not a common root`));const a=t.joints.indexOf(e.index);return r=new la(e.name||`joint${e.index}`,i,s,this._getNodeMatrix(e),null,null,a),n[e.index]=r,this._postSceneLoadActions.push((()=>{r.linkTransformNode(e._babylonTransformNode)})),r}_loadSkinInverseBindMatricesDataAsync(e,t){if(null==t.inverseBindMatrices)return Promise.resolve(null);const i=io.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=k.Identity(),n=i._index;t&&-1!==n&&(k.FromArrayToRef(t,16*n,e),e.invertToRef(e));const r=i.getParent();r&&e.multiplyToRef(r.getAbsoluteInverseBindMatrix(),e),i.updateMatrix(e,!1,!1),i._updateAbsoluteBindMatrices(void 0,!1)}}_getNodeMatrix(e){return e.matrix?k.FromArray(e.matrix):k.Compose(e.scale?B.FromArray(e.scale):B.One(),e.rotation?V.FromArray(e.rotation):V.Identity(),e.translation?B.FromArray(e.translation):B.Zero())}loadCameraAsync(e,t,i=()=>{}){const n=this._extensionsLoadCameraAsync(e,t,i);if(n)return n;const r=new Array;this.logOpen(`${e} ${t.name||""}`),this._babylonScene._blockEntityCollection=!!this._assetContainer;const s=new Ca(t.name||`camera${t.index}`,B.Zero(),this._babylonScene,!1);switch(s._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,s.ignoreParentScaling=!0,t._babylonCamera=s,s.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`);s.fov=i.yfov,s.minZ=i.znear,s.maxZ=i.zfar||0;break}case"orthographic":if(!t.orthographic)throw new Error(`${e}: Camera orthographic properties are missing`);s.mode=ii.ORTHOGRAPHIC_CAMERA,s.orthoLeft=-t.orthographic.xmag,s.orthoRight=t.orthographic.xmag,s.orthoBottom=-t.orthographic.ymag,s.orthoTop=t.orthographic.ymag,s.minZ=t.orthographic.znear,s.maxZ=t.orthographic.zfar;break;default:throw new Error(`${e}: Invalid camera type (${t.type})`)}return no.AddPointerMetadata(s,e),this._parent.onCameraLoadedObservable.notifyObservers(s),i(s),this.logClose(),Promise.all(r).then((()=>s))}_loadAnimationsAsync(){const e=this._gltf.animations;if(!e)return Promise.resolve();const t=new Array;for(let i=0;i<e.length;i++){const n=e[i];t.push(this.loadAnimationAsync(`/animations/${n.index}`,n).then((e=>{0===e.targetedAnimations.length&&e.dispose()})))}return Promise.all(t).then((()=>{}))}loadAnimationAsync(e,t){const i=this._extensionsLoadAnimationAsync(e,t);if(i)return i;this._babylonScene._blockEntityCollection=!!this._assetContainer;const n=new xa(t.name||`animation${t.index}`,this._babylonScene);n._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,t._babylonAnimationGroup=n;const r=new Array;io.Assign(t.channels),io.Assign(t.samplers);for(const i of t.channels)r.push(this._loadAnimationChannelAsync(`${e}/channels/${i.index}`,e,t,i,((e,t)=>{e.animations=e.animations||[],e.animations.push(t),n.addTargetedAnimation(t,e)})));return Promise.all(r).then((()=>(n.normalize(0),n)))}_loadAnimationChannelAsync(e,t,i,n,r){const s=this._extensionsLoadAnimationChannelAsync(e,t,i,n,r);if(s)return s;if(null==n.target.node)return Promise.resolve();const a=io.Get(`${e}/target/node`,this._gltf.nodes,n.target.node),o=n.target.path,l="weights"===o;if(l&&!a._numMorphTargets||!l&&!a._babylonTransformNode)return Promise.resolve();if(!this._parent.loadNodeAnimations&&!l&&!a._isJoint)return Promise.resolve();let c;switch(o){case"translation":c=eo.translation;break;case"rotation":c=eo.rotation;break;case"scale":c=eo.scale;break;case"weights":c=eo.weights;break;default:throw new Error(`${e}/target/path: Invalid value (${n.target.path})`)}const h={object:a,info:c};return this._loadAnimationChannelFromTargetInfoAsync(e,t,i,n,h,r)}_loadAnimationChannelFromTargetInfoAsync(e,t,i,n,r,s){const a=this.parent.targetFps,o=1/a,l=io.Get(`${e}/sampler`,i.samplers,n.sampler);return this._loadAnimationSamplerAsync(`${t}/samplers/${n.sampler}`,l).then((e=>{let t=0;const l=r.object,c=r.info;for(const r of c){const c=r.getStride(l),h=e.input,d=e.output,u=new Array(h.length);let f=0;switch(e.interpolation){case"STEP":for(let e=0;e<h.length;e++){const t=r.getValue(l,d,f,1);f+=c,u[e]={frame:h[e]*a,value:t,interpolation:1}}break;case"CUBICSPLINE":for(let e=0;e<h.length;e++){const t=r.getValue(l,d,f,o);f+=c;const i=r.getValue(l,d,f,1);f+=c;const n=r.getValue(l,d,f,o);f+=c,u[e]={frame:h[e]*a,inTangent:t,value:i,outTangent:n}}break;case"LINEAR":for(let e=0;e<h.length;e++){const t=r.getValue(l,d,f,1);f+=c,u[e]={frame:h[e]*a,value:t}}}if(f>0){const e=`${i.name||`animation${i.index}`}_channel${n.index}_${t}`;r.buildAnimations(l,e,a,u,((e,i)=>{++t,s(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 n=io.Get(`${e}/input`,this._gltf.accessors,t.input),r=io.Get(`${e}/output`,this._gltf.accessors,t.output);return t._data=Promise.all([this._loadFloatAccessorAsync(`/accessors/${n.index}`,n),this._loadFloatAccessorAsync(`/accessors/${r.index}`,r)]).then((([e,t])=>({input:e,interpolation:i,output:t}))),t._data}loadBufferAsync(e,t,i,n){const r=this._extensionsLoadBufferAsync(e,t,i,n);if(r)return r;if(!t._data)if(t.uri)t._data=this.loadUriAsync(`${e}/uri`,t,t.uri);else{if(!this._bin)throw new Error(`${e}: Uri is missing or the binary glTF is missing its binary chunk`);t._data=this._bin.readAsync(0,t.byteLength)}return t._data.then((t=>{try{return new Uint8Array(t.buffer,t.byteOffset+i,n)}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 n=io.Get(`${e}/buffer`,this._gltf.buffers,t.buffer);return t._data=this.loadBufferAsync(`/buffers/${n.index}`,n,t.byteOffset||0,t.byteLength),t._data}_loadAccessorAsync(e,t,i){if(t._data)return t._data;const n=no._GetNumComponents(e,t.type),r=n*si.GetTypeByteLength(t.componentType),s=n*t.count;if(null==t.bufferView)t._data=Promise.resolve(new i(s));else{const a=io.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._data=this.loadBufferViewAsync(`/bufferViews/${a.index}`,a).then((o=>{if(5126!==t.componentType||t.normalized||a.byteStride&&a.byteStride!==r){const e=new i(s);return si.ForEach(o,t.byteOffset||0,a.byteStride||r,n,t.componentType,e.length,t.normalized||!1,((t,i)=>{e[i]=t})),e}return no._GetTypedArray(e,t.componentType,o,t.byteOffset,s)}))}if(t.sparse){const s=t.sparse;t._data=t._data.then((a=>{const o=a,l=io.Get(`${e}/sparse/indices/bufferView`,this._gltf.bufferViews,s.indices.bufferView),c=io.Get(`${e}/sparse/values/bufferView`,this._gltf.bufferViews,s.values.bufferView);return Promise.all([this.loadBufferViewAsync(`/bufferViews/${l.index}`,l),this.loadBufferViewAsync(`/bufferViews/${c.index}`,c)]).then((([a,l])=>{const c=no._GetTypedArray(`${e}/sparse/indices`,s.indices.componentType,a,s.indices.byteOffset,s.count),h=n*s.count;let d;if(5126!==t.componentType||t.normalized){const a=no._GetTypedArray(`${e}/sparse/values`,t.componentType,l,s.values.byteOffset,h);d=new i(h),si.ForEach(a,0,r,n,t.componentType,d.length,t.normalized||!1,((e,t)=>{d[t]=e}))}else d=no._GetTypedArray(`${e}/sparse/values`,t.componentType,l,s.values.byteOffset,h);let u=0;for(let e=0;e<c.length;e++){let t=c[e]*n;for(let e=0;e<n;e++)o[t++]=d[u++]}return o}))}))}return t._data}_loadFloatAccessorAsync(e,t){return this._loadAccessorAsync(e,t,Float32Array)}_loadIndicesAccessorAsync(e,t){if("SCALAR"!==t.type)throw new Error(`${e}/type: Invalid value ${t.type}`);if(5121!==t.componentType&&5123!==t.componentType&&5125!==t.componentType)throw new Error(`${e}/componentType: Invalid value ${t.componentType}`);if(t._data)return t._data;if(t.sparse){const i=no._GetTypedArrayConstructor(`${e}/componentType`,t.componentType);t._data=this._loadAccessorAsync(e,t,i)}else{const i=io.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._data=this.loadBufferViewAsync(`/bufferViews/${i.index}`,i).then((i=>no._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 ri(t,e,!1))),e._babylonBuffer}_loadVertexAccessorAsync(e,t,i){if(t._babylonVertexBuffer?.[i])return t._babylonVertexBuffer[i];t._babylonVertexBuffer||(t._babylonVertexBuffer={});const n=this._babylonScene.getEngine();if(t.sparse||null==t.bufferView)t._babylonVertexBuffer[i]=this._loadFloatAccessorAsync(e,t).then((e=>new si(n,e,i,!1)));else{const r=io.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._babylonVertexBuffer[i]=this._loadVertexBufferViewAsync(r).then((s=>{const a=no._GetNumComponents(e,t.type);return new si(n,s,i,!1,void 0,r.byteStride,void 0,t.byteOffset,a,t.componentType,t.normalized,!0,void 0,!0)}))}return t._babylonVertexBuffer[i]}_loadMaterialMetallicRoughnessPropertiesAsync(e,t,i){if(!(i instanceof Hs))throw new Error(`${e}: Material type not supported`);const n=new Array;return t&&(t.baseColorFactor?(i.albedoColor=ee.FromArray(t.baseColorFactor),i.alpha=t.baseColorFactor[3]):i.albedoColor=ee.White(),i.metallic=null==t.metallicFactor?1:t.metallicFactor,i.roughness=null==t.roughnessFactor?1:t.roughnessFactor,t.baseColorTexture&&n.push(this.loadTextureInfoAsync(`${e}/baseColorTexture`,t.baseColorTexture,(e=>{e.name=`${i.name} (Base Color)`,i.albedoTexture=e}))),t.metallicRoughnessTexture&&(t.metallicRoughnessTexture.nonColorData=!0,n.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(n).then((()=>{}))}_loadMaterialAsync(e,t,i,n,r=()=>{}){const s=this._extensionsLoadMaterialAsync(e,t,i,n,r);if(s)return s;t._data=t._data||{};let a=t._data[n];if(!a){this.logOpen(`${e} ${t.name||""}`);const i=this.createMaterial(e,t,n);a={babylonMaterial:i,babylonMeshes:[],promise:this.loadMaterialPropertiesAsync(e,t,i)},t._data[n]=a,no.AddPointerMetadata(i,e),this._parent.onMaterialLoadedObservable.notifyObservers(i),this.logClose()}return i&&(a.babylonMeshes.push(i),i.onDisposeObservable.addOnce((()=>{const e=a.babylonMeshes.indexOf(i);-1!==e&&a.babylonMeshes.splice(e,1)}))),r(a.babylonMaterial),a.promise.then((()=>a.babylonMaterial))}_createDefaultMaterial(e,t){this._babylonScene._blockEntityCollection=!!this._assetContainer;const i=new Hs(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=Hs.PBRMATERIAL_OPAQUE,i.metallic=1,i.roughness=1,i}createMaterial(e,t,i){const n=this._extensionsCreateMaterial(e,t,i);if(n)return n;const r=t.name||`material${t.index}`;return this._createDefaultMaterial(r,i)}loadMaterialPropertiesAsync(e,t,i){const n=this._extensionsLoadMaterialPropertiesAsync(e,t,i);if(n)return n;const r=new Array;return r.push(this.loadMaterialBasePropertiesAsync(e,t,i)),t.pbrMetallicRoughness&&r.push(this._loadMaterialMetallicRoughnessPropertiesAsync(`${e}/pbrMetallicRoughness`,t.pbrMetallicRoughness,i)),this.loadMaterialAlphaProperties(e,t,i),Promise.all(r).then((()=>{}))}loadMaterialBasePropertiesAsync(e,t,i){if(!(i instanceof Hs))throw new Error(`${e}: Material type not supported`);const n=new Array;return i.emissiveColor=t.emissiveFactor?ee.FromArray(t.emissiveFactor):new ee(0,0,0),t.doubleSided&&(i.backFaceCulling=!1,i.twoSidedLighting=!0),t.normalTexture&&(t.normalTexture.nonColorData=!0,n.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,n.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&&n.push(this.loadTextureInfoAsync(`${e}/emissiveTexture`,t.emissiveTexture,(e=>{e.name=`${i.name} (Emissive)`,i.emissiveTexture=e}))),Promise.all(n).then((()=>{}))}loadMaterialAlphaProperties(e,t,i){if(!(i instanceof Hs))throw new Error(`${e}: Material type not supported`);switch(t.alphaMode||"OPAQUE"){case"OPAQUE":i.transparencyMode=Hs.PBRMATERIAL_OPAQUE,i.alpha=1;break;case"MASK":i.transparencyMode=Hs.PBRMATERIAL_ALPHATEST,i.alphaCutOff=null==t.alphaCutoff?.5:t.alphaCutoff,i.albedoTexture&&(i.albedoTexture.hasAlpha=!0);break;case"BLEND":i.transparencyMode=Hs.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 n=this._extensionsLoadTextureInfoAsync(e,t,i);if(n)return n;if(this.logOpen(`${e}`),t.texCoord>=6)throw new Error(`${e}/texCoord: Invalid value (${t.texCoord})`);const r=io.Get(`${e}/index`,this._gltf.textures,t.index);r._textureInfo=t;const s=this._loadTextureAsync(`/textures/${t.index}`,r,(n=>{n.coordinatesIndex=t.texCoord||0,no.AddPointerMetadata(n,e),this._parent.onTextureLoadedObservable.notifyObservers(n),i(n)}));return this.logClose(),s}_loadTextureAsync(e,t,i=()=>{}){const n=this._extensionsLoadTextureAsync(e,t,i);if(n)return n;this.logOpen(`${e} ${t.name||""}`);const r=null==t.sampler?no.DefaultSampler:io.Get(`${e}/sampler`,this._gltf.samplers,t.sampler),s=io.Get(`${e}/source`,this._gltf.images,t.source),a=this._createTextureAsync(e,r,s,i,void 0,!t._textureInfo.nonColorData);return this.logClose(),a}_createTextureAsync(e,t,i,n=()=>{},r,s){const a=this._loadSampler(`/samplers/${t.index}`,t),o=new Array,l=new sa;this._babylonScene._blockEntityCollection=!!this._assetContainer;const c={noMipmap:a.noMipMaps,invertY:!1,samplingMode:a.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:r,useSRGBBuffer:!!s&&this._parent.useSRGBBuffers},h=new Pr(null,this._babylonScene,c);return h._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,o.push(l.promise),o.push(this.loadImageAsync(`/images/${i.index}`,i).then((e=>{const t=i.uri||`${this._fileName}#image${i.index}`,n=`data:${this._uniqueRootUrl}${t}`;h.updateURL(n,e)}))),h.wrapU=a.wrapU,h.wrapV=a.wrapV,n(h),Promise.all(o).then((()=>h))}_loadSampler(e,t){return t._data||(t._data={noMipMaps:9728===t.minFilter||9729===t.minFilter,samplingMode:no._GetTextureSamplingMode(e,t),wrapU:no._GetTextureWrapMode(`${e}/wrapS`,t.wrapS),wrapV:no._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=io.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 n=this._extensionsLoadUriAsync(e,t,i);if(n)return n;if(!no._ValidateUri(i))throw new Error(`${e}: '${i}' is invalid`);if(Pt(i)){const t=new Uint8Array(Ft(i));return this.log(`${e}: Decoded ${i.substr(0,64)}... (${t.length} bytes)`),Promise.resolve(t)}return this.log(`${e}: Loading ${i}`),this._parent.preprocessUrlAsync(this._rootUrl+i).then((t=>new Promise(((n,r)=>{this._parent._loadFile(this._babylonScene,t,(t=>{this._disposed||(this.log(`${e}: Loaded ${i} (${t.byteLength} bytes)`),n(new Uint8Array(t)))}),!0,(t=>{r(new St(`${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||{},n=i.gltf=i.gltf||{};(n.pointers=n.pointers||[]).push(t)}static _GetTextureWrapMode(e,t){switch(t=null==t?10497:t){case 33071:return Pr.CLAMP_ADDRESSMODE;case 33648:return Pr.MIRROR_ADDRESSMODE;case 10497:return Pr.WRAP_ADDRESSMODE;default:return de.Warn(`${e}: Invalid value (${t})`),Pr.WRAP_ADDRESSMODE}}static _GetTextureSamplingMode(e,t){const i=null==t.magFilter?9729:t.magFilter,n=null==t.minFilter?9987:t.minFilter;if(9729===i)switch(n){case 9728:return Pr.LINEAR_NEAREST;case 9729:return Pr.LINEAR_LINEAR;case 9984:return Pr.LINEAR_NEAREST_MIPNEAREST;case 9985:return Pr.LINEAR_LINEAR_MIPNEAREST;case 9986:return Pr.LINEAR_NEAREST_MIPLINEAR;case 9987:return Pr.LINEAR_LINEAR_MIPLINEAR;default:return de.Warn(`${e}/minFilter: Invalid value (${n})`),Pr.LINEAR_LINEAR_MIPLINEAR}else switch(9728!==i&&de.Warn(`${e}/magFilter: Invalid value (${i})`),n){case 9728:return Pr.NEAREST_NEAREST;case 9729:return Pr.NEAREST_LINEAR;case 9984:return Pr.NEAREST_NEAREST_MIPNEAREST;case 9985:return Pr.NEAREST_LINEAR_MIPNEAREST;case 9986:return Pr.NEAREST_NEAREST_MIPLINEAR;case 9987:return Pr.NEAREST_LINEAR_MIPLINEAR;default:return de.Warn(`${e}/minFilter: Invalid value (${n})`),Pr.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,n,r){const s=i.buffer;n=i.byteOffset+(n||0);const a=no._GetTypedArrayConstructor(`${e}/componentType`,t),o=si.GetTypeByteLength(t);return n%o!=0?(de.Warn(`${e}: Copying buffer as byte offset (${n}) is not a multiple of component type byte length (${o})`),new a(s.slice(n,n+r*o),0)):new a(s,n,r)}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 Yt.IsBase64(e)||-1===e.indexOf("..")}static _GetDrawMode(e,t){switch(null==t&&(t=4),t){case 0:return Ji.PointListDrawMode;case 1:return Ji.LineListDrawMode;case 2:return Ji.LineLoopDrawMode;case 3:return Ji.LineStripDrawMode;case 4:return Ji.TriangleFillMode;case 5:return Ji.TriangleStripDrawMode;case 6:return Ji.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 n=t._data[i];for(const t of n.babylonMeshes){t.computeWorldMatrix(!0);const i=n.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 n of this._extensions)if(n.enabled){const r=`${n.name}.${t}`,s=e;s._activeLoaderExtensionFunctions=s._activeLoaderExtensionFunctions||{};const a=s._activeLoaderExtensionFunctions;if(!a[r]){a[r]=!0;try{const e=i(n);if(e)return e}finally{delete a[r]}}}return null}_extensionsOnLoading(){this._forEachExtensions((e=>e.onLoading&&e.onLoading()))}_extensionsOnReady(){this._forEachExtensions((e=>e.onReady&&e.onReady()))}_extensionsLoadSceneAsync(e,t){return this._applyExtensions(t,"loadScene",(i=>i.loadSceneAsync&&i.loadSceneAsync(e,t)))}_extensionsLoadNodeAsync(e,t,i){return this._applyExtensions(t,"loadNode",(n=>n.loadNodeAsync&&n.loadNodeAsync(e,t,i)))}_extensionsLoadCameraAsync(e,t,i){return this._applyExtensions(t,"loadCamera",(n=>n.loadCameraAsync&&n.loadCameraAsync(e,t,i)))}_extensionsLoadVertexDataAsync(e,t,i){return this._applyExtensions(t,"loadVertexData",(n=>n._loadVertexDataAsync&&n._loadVertexDataAsync(e,t,i)))}_extensionsLoadMeshPrimitiveAsync(e,t,i,n,r,s){return this._applyExtensions(r,"loadMeshPrimitive",(a=>a._loadMeshPrimitiveAsync&&a._loadMeshPrimitiveAsync(e,t,i,n,r,s)))}_extensionsLoadMaterialAsync(e,t,i,n,r){return this._applyExtensions(t,"loadMaterial",(s=>s._loadMaterialAsync&&s._loadMaterialAsync(e,t,i,n,r)))}_extensionsCreateMaterial(e,t,i){return this._applyExtensions(t,"createMaterial",(n=>n.createMaterial&&n.createMaterial(e,t,i)))}_extensionsLoadMaterialPropertiesAsync(e,t,i){return this._applyExtensions(t,"loadMaterialProperties",(n=>n.loadMaterialPropertiesAsync&&n.loadMaterialPropertiesAsync(e,t,i)))}_extensionsLoadTextureInfoAsync(e,t,i){return this._applyExtensions(t,"loadTextureInfo",(n=>n.loadTextureInfoAsync&&n.loadTextureInfoAsync(e,t,i)))}_extensionsLoadTextureAsync(e,t,i){return this._applyExtensions(t,"loadTexture",(n=>n._loadTextureAsync&&n._loadTextureAsync(e,t,i)))}_extensionsLoadAnimationAsync(e,t){return this._applyExtensions(t,"loadAnimation",(i=>i.loadAnimationAsync&&i.loadAnimationAsync(e,t)))}_extensionsLoadAnimationChannelAsync(e,t,i,n,r){return this._applyExtensions(i,"loadAnimationChannel",(s=>s._loadAnimationChannelAsync&&s._loadAnimationChannelAsync(e,t,i,n,r)))}_extensionsLoadSkinAsync(e,t,i){return this._applyExtensions(i,"loadSkin",(n=>n._loadSkinAsync&&n._loadSkinAsync(e,t,i)))}_extensionsLoadUriAsync(e,t,i){return this._applyExtensions(t,"loadUri",(n=>n._loadUriAsync&&n._loadUriAsync(e,t,i)))}_extensionsLoadBufferViewAsync(e,t){return this._applyExtensions(t,"loadBufferView",(i=>i.loadBufferViewAsync&&i.loadBufferViewAsync(e,t)))}_extensionsLoadBufferAsync(e,t,i,n){return this._applyExtensions(t,"loadBuffer",(r=>r.loadBufferAsync&&r.loadBufferAsync(e,t,i,n)))}static LoadExtensionAsync(e,t,i,n){if(!t.extensions)return null;const r=t.extensions[i];return r?n(`${e}/extensions/${i}`,r):null}static LoadExtraAsync(e,t,i,n){if(!t.extras)return null;const r=t.extras[i];return r?n(`${e}/extras/${i}`,r):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)}}no._RegisteredExtensions={},no.DefaultSampler={index:-1},Qa._CreateGLTF2Loader=e=>new no(e);class ro extends Js{constructor(e,t,i,n=Ze.TEXTUREFORMAT_RGBA,r=Ze.TEXTURETYPE_UNSIGNED_INT,s=!1,a=!1,o=Ze.TEXTURE_TRILINEAR_SAMPLINGMODE,l=null){super("",e),this._texture=e.getEngine().createRawCubeTexture(t,i,n,r,s,a,o,l)}update(e,t,i,n,r=null){this._texture.getEngine().updateRawCubeTexture(this._texture,e,t,i,n,r)}updateRGBDAsync(e,t=null,i=.8,n=0){return function(e,t,i,n,r){const s=pa(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:s,isReady:!0,isAsync:!0}),e._source=13,e._bufferViewArrayArray=t,e._lodGenerationScale=n,e._lodGenerationOffset=r,e._sphericalPolynomial=i,pa(e,t).then((()=>(e.isReady=!0,e)))}(this._texture,e,t,i,n).then((()=>{}))}clone(){return re.Clone((()=>{const e=this.getScene(),t=this._texture,i=new ro(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)}}const so="EXT_lights_image_based";class ao{constructor(e){this.name=so,this._loader=e,this.enabled=this._loader.isExtensionUsed(so)}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 no.LoadExtensionAsync(e,t,this.name,((i,n)=>{this._loader._allMaterialsDirtyRequired=!0;const r=new Array;r.push(this._loader.loadSceneAsync(e,t)),this._loader.logOpen(`${i}`);const s=io.Get(`${i}/light`,this._lights,n.light);return r.push(this._loadLightAsync(`/extensions/${this.name}/lights/${n.light}`,s).then((e=>{this._loader.babylonScene.environmentTexture=e}))),this._loader.logClose(),Promise.all(r).then((()=>{}))}))}_loadLightAsync(e,t){if(!t._loaded){const i=new Array;this._loader.logOpen(`${e}`);const n=new Array(t.specularImages.length);for(let r=0;r<t.specularImages.length;r++){const s=t.specularImages[r];n[r]=new Array(s.length);for(let t=0;t<s.length;t++){const a=`${e}/specularImages/${r}/${t}`;this._loader.logOpen(`${a}`);const o=s[t],l=io.Get(a,this._loader.gltf.images,o);i.push(this._loader.loadImageAsync(`/images/${o}`,l).then((e=>{n[r][t]=e}))),this._loader.logClose()}}this._loader.logClose(),t._loaded=Promise.all(i).then((()=>{const i=new ro(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=V.FromArray(t.rotation);this._loader.babylonScene.useRightHandedSystem||(e=V.Inverse(e)),k.FromQuaternionToRef(e,i.getReflectionTextureMatrix())}if(!t.irradianceCoefficients)throw new Error(`${e}: Irradiance coefficients are missing`);const r=Ss.FromArray(t.irradianceCoefficients);r.scaleInPlace(t.intensity),r.convertIrradianceToLambertianRadiance();const s=Is.FromHarmonics(r),a=(n.length-1)/j.Log2(t.specularImageSize);return i.updateRGBDAsync(n,s,a)}))}return t._loaded.then((()=>t._babylonTexture))}}no.RegisterExtension(so,(e=>new ao(e))),ln.prototype.thinInstanceAdd=function(e,t=!0){if(!this.getScene().getEngine().getCaps().instancedArrays)return de.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<e.length;++i)this.thinInstanceSetMatrixAt(this._thinInstanceDataStorage.instancesCount++,e[i],i===e.length-1&&t);else this.thinInstanceSetMatrixAt(this._thinInstanceDataStorage.instancesCount++,e,t);return i},ln.prototype.thinInstanceAddSelf=function(e=!0){return this.thinInstanceAdd(k.IdentityReadOnly,e)},ln.prototype.thinInstanceRegisterAttribute=function(e,t){e===si.ColorKind&&(e=si.ColorInstanceKind),this.removeVerticesData(e),this._thinInstanceInitializeUserStorage(),this._userThinInstanceBuffersStorage.strides[e]=t,this._userThinInstanceBuffersStorage.sizes[e]=t*Math.max(32,this._thinInstanceDataStorage.instancesCount),this._userThinInstanceBuffersStorage.data[e]=new Float32Array(this._userThinInstanceBuffersStorage.sizes[e]),this._userThinInstanceBuffersStorage.vertexBuffers[e]=new si(this.getEngine(),this._userThinInstanceBuffersStorage.data[e],e,!0,!1,t,!0),this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[e])},ln.prototype.thinInstanceSetMatrixAt=function(e,t,i=!0){if(!this._thinInstanceDataStorage.matrixData||e>=this._thinInstanceDataStorage.instancesCount)return!1;const n=this._thinInstanceDataStorage.matrixData;return t.copyToArray(n,16*e),this._thinInstanceDataStorage.worldMatrices&&(this._thinInstanceDataStorage.worldMatrices[e]=t),i&&(this.thinInstanceBufferUpdated("matrix"),this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1)),!0},ln.prototype.thinInstanceSetAttributeAt=function(e,t,i,n=!0){return e===si.ColorKind&&(e=si.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]),n&&this.thinInstanceBufferUpdated(e),!0)},Object.defineProperty(ln.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}),ln.prototype._thinInstanceCreateMatrixBuffer=function(e,t,i=!0){const n=new ri(this.getEngine(),t,!i,16,!1,!0);for(let t=0;t<4;t++)this.setVerticesBuffer(n.createVertexBuffer(e+t,4*t,4));return n},ln.prototype.thinInstanceSetBuffer=function(e,t,i=0,n=!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,n),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,n))):(e===si.ColorKind&&(e=si.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 si(this.getEngine(),t,e,!n,!1,i,!0),this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[e])))},ln.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===si.ColorKind&&(e=si.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)))},ln.prototype.thinInstancePartialBufferUpdate=function(e,t,i){"matrix"===e?this._thinInstanceDataStorage.matrixBuffer&&this._thinInstanceDataStorage.matrixBuffer.updateDirectly(t,i):(e===si.ColorKind&&(e=si.ColorInstanceKind),this._userThinInstanceBuffersStorage?.vertexBuffers[e]&&this._userThinInstanceBuffersStorage.vertexBuffers[e].updateDirectly(t,i))},ln.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;t<this._thinInstanceDataStorage.instancesCount;++t)this._thinInstanceDataStorage.worldMatrices[t]=k.FromArray(e,16*t)}return this._thinInstanceDataStorage.worldMatrices},ln.prototype.thinInstanceRefreshBoundingInfo=function(e=!1,t=!1,i=!1){if(!this._thinInstanceDataStorage.matrixData||!this._thinInstanceDataStorage.matrixBuffer)return;const n=this._thinInstanceDataStorage.boundingVectors;if(e||!this.rawBoundingInfo){n.length=0,this.refreshBoundingInfo(t,i);const e=this.getBoundingInfo();this.rawBoundingInfo=new fi(e.minimum,e.maximum)}const r=this.getBoundingInfo(),s=this._thinInstanceDataStorage.matrixData;if(0===n.length)for(let e=0;e<r.boundingBox.vectors.length;++e)n.push(r.boundingBox.vectors[e].clone());H.Vector3[0].setAll(Number.POSITIVE_INFINITY),H.Vector3[1].setAll(Number.NEGATIVE_INFINITY);for(let e=0;e<this._thinInstanceDataStorage.instancesCount;++e){k.FromArrayToRef(s,16*e,H.Matrix[0]);for(let e=0;e<n.length;++e)B.TransformCoordinatesToRef(n[e],H.Matrix[0],H.Vector3[2]),H.Vector3[0].minimizeInPlace(H.Vector3[2]),H.Vector3[1].maximizeInPlace(H.Vector3[2])}r.reConstruct(H.Vector3[0],H.Vector3[1]),this._updateBoundingInfo()},ln.prototype._thinInstanceRecreateBuffer=function(e,t=!0){"matrix"===e?(this._thinInstanceDataStorage.matrixBuffer?.dispose(),this._thinInstanceDataStorage.matrixBuffer=this._thinInstanceCreateMatrixBuffer("world",this._thinInstanceDataStorage.matrixData,t)):"previousMatrix"===e?this._scene.needsPreviousWorldMatrices&&(this._thinInstanceDataStorage.previousMatrixBuffer?.dispose(),this._thinInstanceDataStorage.previousMatrixBuffer=this._thinInstanceCreateMatrixBuffer("previousWorld",this._thinInstanceDataStorage.previousMatrixData??this._thinInstanceDataStorage.matrixData,t)):(e===si.ColorKind&&(e=si.ColorInstanceKind),this._userThinInstanceBuffersStorage.vertexBuffers[e]?.dispose(),this._userThinInstanceBuffersStorage.vertexBuffers[e]=new si(this.getEngine(),this._userThinInstanceBuffersStorage.data[e],e,!t,!1,this._userThinInstanceBuffersStorage.strides[e],!0),this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[e]))},ln.prototype._thinInstanceUpdateBufferSize=function(e,t=1){e===si.ColorKind&&(e=si.ColorInstanceKind);const i="matrix"===e;if(!(i||this._userThinInstanceBuffersStorage&&this._userThinInstanceBuffersStorage.strides[e]))return;const n=i?16:this._userThinInstanceBuffersStorage.strides[e],r=i?this._thinInstanceDataStorage.matrixBufferSize:this._userThinInstanceBuffersStorage.sizes[e];let s=i?this._thinInstanceDataStorage.matrixData:this._userThinInstanceBuffersStorage.data[e];const a=(this._thinInstanceDataStorage.instancesCount+t)*n;let o=r;for(;o<a;)o*=2;if(!s||r!=o){if(s){const e=new Float32Array(o);e.set(s,0),s=e}else s=new Float32Array(o);i?(this._thinInstanceDataStorage.matrixBuffer?.dispose(),this._thinInstanceDataStorage.matrixBuffer=this._thinInstanceCreateMatrixBuffer("world",s,!1),this._thinInstanceDataStorage.matrixData=s,this._thinInstanceDataStorage.matrixBufferSize=o,this._scene.needsPreviousWorldMatrices&&!this._thinInstanceDataStorage.previousMatrixData&&(this._thinInstanceDataStorage.previousMatrixBuffer?.dispose(),this._thinInstanceDataStorage.previousMatrixBuffer=this._thinInstanceCreateMatrixBuffer("previousWorld",s,!1))):(this._userThinInstanceBuffersStorage.vertexBuffers[e]?.dispose(),this._userThinInstanceBuffersStorage.data[e]=s,this._userThinInstanceBuffersStorage.sizes[e]=o,this._userThinInstanceBuffersStorage.vertexBuffers[e]=new si(this.getEngine(),s,e,!0,!1,n,!0),this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[e]))}},ln.prototype._thinInstanceInitializeUserStorage=function(){this._userThinInstanceBuffersStorage||(this._userThinInstanceBuffersStorage={data:{},sizes:{},vertexBuffers:{},strides:{}})},ln.prototype._disposeThinInstanceSpecificData=function(){this._thinInstanceDataStorage?.matrixBuffer&&(this._thinInstanceDataStorage.matrixBuffer.dispose(),this._thinInstanceDataStorage.matrixBuffer=null)};const oo="EXT_mesh_gpu_instancing";class lo{constructor(e){this.name=oo,this._loader=e,this.enabled=this._loader.isExtensionUsed(oo)}dispose(){this._loader=null}loadNodeAsync(e,t,i){return no.LoadExtensionAsync(e,t,this.name,((e,n)=>{this._loader._disableInstancedMesh++;const r=this._loader.loadNodeAsync(`/nodes/${t.index}`,t,i);if(this._loader._disableInstancedMesh--,!t._primitiveBabylonMeshes)return r;const s=new Array;let a=0;const o=t=>{if(null==n.attributes[t])return void s.push(Promise.resolve(null));const i=io.Get(`${e}/attributes/${t}`,this._loader.gltf.accessors,n.attributes[t]);if(s.push(this._loader._loadFloatAccessorAsync(`/accessors/${i.bufferView}`,i)),0===a)a=i.count;else if(a!==i.count)throw new Error(`${e}/attributes: Instance buffer accessors do not have the same count.`)};return o("TRANSLATION"),o("ROTATION"),o("SCALE"),r.then((e=>Promise.all(s).then((([i,n,r])=>{const s=new Float32Array(16*a);H.Vector3[0].copyFromFloats(0,0,0),H.Quaternion[0].copyFromFloats(0,0,0,1),H.Vector3[1].copyFromFloats(1,1,1);for(let e=0;e<a;++e)i&&B.FromArrayToRef(i,3*e,H.Vector3[0]),n&&V.FromArrayToRef(n,4*e,H.Quaternion[0]),r&&B.FromArrayToRef(r,3*e,H.Vector3[1]),k.ComposeToRef(H.Vector3[1],H.Quaternion[0],H.Vector3[0],H.Matrix[0]),H.Matrix[0].copyToArray(s,16*e);for(const e of t._primitiveBabylonMeshes)e.thinInstanceSetBuffer("matrix",s,16,!0);return e}))))}))}}no.RegisterExtension(oo,(e=>new lo(e)));class co{static get Default(){return co._Default||(co._Default=new co),co._Default}constructor(){const e=co.Configuration.decoder;this._decoderModulePromise=Yt.LoadBabylonScriptAsync(e.url).then((()=>MeshoptDecoder.ready))}dispose(){delete this._decoderModulePromise}decodeGltfBufferAsync(e,t,i,n,r){return this._decoderModulePromise.then((async()=>{MeshoptDecoder.useWorkers(1);const s=await MeshoptDecoder.decodeGltfBufferAsync(t,i,e,n,r);return MeshoptDecoder.useWorkers(0),s}))}}co.Configuration={decoder:{url:`${Yt._DefaultCdnUrl}/meshopt_decoder.js`}},co._Default=null;const ho="EXT_meshopt_compression";class uo{constructor(e){this.name=ho,this.enabled=e.isExtensionUsed(ho),this._loader=e}dispose(){this._loader=null}loadBufferViewAsync(e,t){return no.LoadExtensionAsync(e,t,this.name,((i,n)=>{const r=t;if(r._meshOptData)return r._meshOptData;const s=io.Get(`${e}/buffer`,this._loader.gltf.buffers,n.buffer);return r._meshOptData=this._loader.loadBufferAsync(`/buffers/${s.index}`,s,n.byteOffset||0,n.byteLength).then((e=>co.Default.decodeGltfBufferAsync(e,n.count,n.byteStride,n.mode,n.filter))),r._meshOptData}))}}no.RegisterExtension(ho,(e=>new uo(e)));const fo="EXT_texture_webp";class _o{constructor(e){this.name=fo,this._loader=e,this.enabled=e.isExtensionUsed(fo)}dispose(){this._loader=null}_loadTextureAsync(e,t,i){return no.LoadExtensionAsync(e,t,this.name,((n,r)=>{const s=null==t.sampler?no.DefaultSampler:io.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),a=io.Get(`${n}/source`,this._loader.gltf.images,r.source);return this._loader._createTextureAsync(e,s,a,(e=>{i(e)}),void 0,!t._textureInfo.nonColorData)}))}}no.RegisterExtension(fo,(e=>new _o(e)));const mo="EXT_texture_avif";class po{constructor(e){this.name=mo,this._loader=e,this.enabled=e.isExtensionUsed(mo)}dispose(){this._loader=null}_loadTextureAsync(e,t,i){return no.LoadExtensionAsync(e,t,this.name,((n,r)=>{const s=null==t.sampler?no.DefaultSampler:io.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),a=io.Get(`${n}/source`,this._loader.gltf.images,r.source);return this._loader._createTextureAsync(e,s,a,(e=>{i(e)}),void 0,!t._textureInfo.nonColorData)}))}}no.RegisterExtension(mo,(e=>new po(e)));class go{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 Eo extends go{constructor(e,t,i=Eo.DefaultOptions){super([]),this._maxWorkers=e,this._createWorkerAsync=t,this._options=i}push(e){if(!this._executeOnIdleWorker(e))if(this._workerInfos.length<this._maxWorkers){const t={workerPromise:this._createWorkerAsync(),idle:!1};this._workerInfos.push(t),this._execute(t,e)}else this._pendingActions.push(e)}_execute(e,t){e.timeoutId&&(clearTimeout(e.timeoutId),delete e.timeoutId),super._execute(e,((i,n)=>{t(i,(()=>{n(),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))}))}))}}function To(e,t,i,n,r){let s=null,a=null,o=null;try{let l;s=new e.Decoder,a=new e.DecoderBuffer,a.Init(t,t.byteLength);const c=s.GetEncodedGeometryType(a);switch(c){case e.TRIANGULAR_MESH:{const t=new e.Mesh;if(l=s.DecodeBufferToMesh(a,t),!l.ok()||0===t.ptr)throw new Error(l.error_msg());const i=3*t.num_faces(),r=4*i,c=e._malloc(r);try{s.GetTrianglesUInt32Array(t,r,c);const a=new Uint32Array(i);a.set(new Uint32Array(e.HEAPF32.buffer,c,i)),n(a)}finally{e._free(c)}o=t;break}case e.POINT_CLOUD:{const t=new e.PointCloud;if(l=s.DecodeBufferToPointCloud(a,t),!l.ok()||!t.ptr)throw new Error(l.error_msg());o=t;break}default:throw new Error(`Invalid geometry type ${c}`)}const h=o.num_points(),d=(t,i,n,s)=>{const a=s.data_type(),o=s.num_components(),l=s.normalized(),c=s.byte_stride(),d=s.byte_offset(),u={[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}}[a];if(!u)throw new Error(`Invalid data type ${a}`);const f=h*o,_=f*u.typedArrayConstructor.BYTES_PER_ELEMENT,m=e._malloc(_);try{t.GetAttributeDataArrayForAllPoints(i,s,a,_,m);const e=new u.typedArrayConstructor(u.heap.buffer,m,f);r(n,e.slice(),o,d,c,l)}finally{e._free(m)}};if(i)for(const e in i){const t=i[e],n=s.GetAttributeByUniqueId(o,t);d(s,o,e,n)}else{const t={position:e.POSITION,normal:e.NORMAL,color:e.COLOR,uv:e.TEX_COORD};for(const e in t){const i=s.GetAttributeId(o,t[e]);if(-1!==i){const t=s.GetAttribute(o,i);d(s,o,e,t)}}}return h}finally{o&&e.destroy(o),a&&e.destroy(a),s&&e.destroy(s)}}function Ao(){let e;onmessage=t=>{const i=t.data;switch(i.id){case"init":{const t=i.decoder;t.url&&importScripts(t.url);const n=t.wasmBinary?{wasmBinary:t.wasmBinary}:{};e=DracoDecoderModule(n),postMessage({id:"initDone"});break}case"decodeMesh":if(!e)throw new Error("Draco decoder module is not available");e.then((e=>{const t=To(e,i.dataView,i.attributes,(e=>{postMessage({id:"indices",data:e},[e.buffer])}),((e,t,i,n,r,s)=>{postMessage({id:"attribute",kind:e,data:t,size:i,byteOffset:n,byteStride:r,normalized:s},[t.buffer])}));postMessage({id:"decodeMeshDone",totalVertices:t})}))}}}Eo.DefaultOptions={idleTimeElapsedBeforeRelease:1e3};class vo{static get DecoderAvailable(){const e=vo.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 vo._Default||(vo._Default=new vo),vo._Default}static ResetDefault(e){vo._Default&&(e||vo._Default.dispose(),vo._Default=null)}constructor(e=vo.DefaultNumWorkers){const t=vo.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,n="number"==typeof e?e:e.numWorkers,r=n&&"function"==typeof Worker&&"function"==typeof URL,s=r||!r&&!t.jsModule,a=t.wasmUrl&&t.wasmBinaryUrl&&"object"==typeof WebAssembly?{url:s?Yt.GetBabylonScriptURL(t.wasmUrl,!0):"",wasmBinaryPromise:i?Promise.resolve(i):Yt.LoadFileAsync(Yt.GetBabylonScriptURL(t.wasmBinaryUrl,!0))}:{url:s?Yt.GetBabylonScriptURL(t.fallbackUrl):"",wasmBinaryPromise:Promise.resolve(void 0)};r?this._workerPoolPromise=a.wasmBinaryPromise.then((e=>{const t=`${To}(${Ao})()`,i=URL.createObjectURL(new Blob([t],{type:"application/javascript"}));return new Eo(n,(()=>function(e,t,i){return new Promise(((n,r)=>{const s=t=>{e.removeEventListener("error",s),e.removeEventListener("message",a),r(t)},a=t=>{"initDone"===t.data.id&&(e.removeEventListener("error",s),e.removeEventListener("message",a),n(e))};if(e.addEventListener("error",s),e.addEventListener("message",a),t){const n=t.slice(0);e.postMessage({id:"init",decoder:{url:i,wasmBinary:n}},[n])}else e.postMessage({id:"init",decoder:{url:i}})}))}(new Worker(i),e,a.url)))})):this._decoderModulePromise=a.wasmBinaryPromise.then((async e=>{if("undefined"==typeof DracoDecoderModule&&!t.jsModule){if(!a.url)throw new Error("Draco decoder module is not available");await Yt.LoadBabylonScriptAsync(a.url)}return await(i=e,n=t.jsModule,new Promise((e=>{(n||DracoDecoderModule)({wasmBinary:i}).then((t=>{e({module:t})}))})));var i,n}))}}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 n=e instanceof ArrayBuffer?new Int8Array(e):new Int8Array(e.buffer,e.byteOffset,e.byteLength);if(this._workerPoolPromise)return this._workerPoolPromise.then((e=>new Promise(((r,s)=>{e.push(((e,a)=>{let o=null;const l=[],c=t=>{e.removeEventListener("error",c),e.removeEventListener("message",h),s(t),a()},h=t=>{const n=t.data;switch(n.id){case"decodeMeshDone":e.removeEventListener("error",c),e.removeEventListener("message",h),r({indices:o,attributes:l,totalVertices:n.totalVertices}),a();break;case"indices":o=n.data;break;case"attribute":l.push({kind:n.kind,data:n.data,size:n.size,byteOffset:n.byteOffset,byteStride:n.byteStride,normalized:(s=n.kind,d=n.normalized,i&&void 0!==i[s]?(d!==i[s]&&de.Warn(`Normalized flag from Draco data (${d}) does not match normalized flag from glTF accessor (${i[s]}). Using flag from glTF accessor.`),i[s]):d)})}var s,d};e.addEventListener("error",c),e.addEventListener("message",h);const d=n.slice();e.postMessage({id:"decodeMesh",dataView:d,attributes:t},[d.buffer])}))}))));if(this._decoderModulePromise)return this._decoderModulePromise.then((e=>{let i=null;const r=[],s=To(e.module,n,t,(e=>{i=e}),((e,t,i,n,s,a)=>{r.push({kind:e,data:t,size:i,byteOffset:n,byteStride:s,normalized:a})}));return{indices:i,attributes:r,totalVertices:s}}));throw new Error("Draco decoder module is not available")}async decodeMeshToGeometryAsync(e,t,i,n){const r=await this.decodeMeshToMeshDataAsync(i,n),s=new vi(e,t);r.indices&&s.setIndices(r.indices);for(const e of r.attributes)s.setVerticesBuffer(new si(t.getEngine(),e.data,e.kind,!1,void 0,e.byteStride,void 0,e.byteOffset,e.size,void 0,e.normalized,!0),r.totalVertices);return s}async _decodeMeshToGeometryForGltfAsync(e,t,i,n,r){const s=await this.decodeMeshToMeshDataAsync(i,n,r),a=new vi(e,t);s.indices&&a.setIndices(s.indices);for(const e of s.attributes)a.setVerticesBuffer(new si(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 a}async decodeMeshAsync(e,t){const i=await this.decodeMeshToMeshDataAsync(e,t),n=new Ti;i.indices&&(n.indices=i.indices);for(const e of i.attributes){const t=si.GetFloatData(e.data,e.size,si.GetDataType(e.data),e.byteOffset,e.byteStride,e.normalized,i.totalVertices);n.set(t,e.kind)}return n}}vo.Configuration={decoder:{wasmUrl:`${Yt._DefaultCdnUrl}/draco_wasm_wrapper_gltf.js`,wasmBinaryUrl:`${Yt._DefaultCdnUrl}/draco_decoder_gltf.wasm`,fallbackUrl:`${Yt._DefaultCdnUrl}/draco_decoder_gltf.js`}},vo.DefaultNumWorkers=vo.GetDefaultNumWorkers(),vo._Default=null;const Ro="KHR_draco_mesh_compression";class So{constructor(e){this.name=Ro,this.useNormalizedFlagFromAccessor=!0,this._loader=e,this.enabled=vo.DecoderAvailable&&this._loader.isExtensionUsed(Ro)}dispose(){delete this.dracoCompression,this._loader=null}_loadVertexDataAsync(e,t,i){return no.LoadExtensionAsync(e,t,this.name,((n,r)=>{if(null!=t.mode&&4!==t.mode&&5!==t.mode)throw new Error(`${e}: Unsupported mode ${t.mode}`);const s={},a={},o=(e,n)=>{const o=r.attributes[e];if(null!=o&&(i._delayInfo=i._delayInfo||[],-1===i._delayInfo.indexOf(n)&&i._delayInfo.push(n),s[n]=o,this.useNormalizedFlagFromAccessor)){const i=io.TryGet(this._loader.gltf.accessors,t.attributes[e]);i&&(a[n]=i.normalized||!1)}};o("POSITION",si.PositionKind),o("NORMAL",si.NormalKind),o("TANGENT",si.TangentKind),o("TEXCOORD_0",si.UVKind),o("TEXCOORD_1",si.UV2Kind),o("TEXCOORD_2",si.UV3Kind),o("TEXCOORD_3",si.UV4Kind),o("TEXCOORD_4",si.UV5Kind),o("TEXCOORD_5",si.UV6Kind),o("JOINTS_0",si.MatricesIndicesKind),o("WEIGHTS_0",si.MatricesWeightsKind),o("COLOR_0",si.ColorKind);const l=io.Get(n,this._loader.gltf.bufferViews,r.bufferView);return l._dracoBabylonGeometry||(l._dracoBabylonGeometry=this._loader.loadBufferViewAsync(`/bufferViews/${l.index}`,l).then((t=>(this.dracoCompression||vo.Default)._decodeMeshToGeometryForGltfAsync(i.name,this._loader.babylonScene,t,s,a).catch((t=>{throw new Error(`${e}: ${t.message}`)}))))),l._dracoBabylonGeometry}))}}no.RegisterExtension(Ro,(e=>new So(e)));class Io extends Xn{constructor(){super(...arguments),this._needProjectionMatrixCompute=!0,this._viewMatrix=k.Identity(),this._projectionMatrix=k.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=B.Zero()),B.TransformCoordinatesToRef(this.position,this.parent.getWorldMatrix(),this.transformedPosition),this.direction&&(this.transformedDirection||(this.transformedDirection=B.Zero()),B.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=B.Normalize(e.subtract(this.position)),this.direction}getRotation(){this.direction.normalize();const e=B.Cross(this.direction,Ui.Y),t=B.Cross(e,this.direction);return B.RotationFromAxis(e,t,this.direction)}needCube(){return!1}needProjectionMatrixCompute(){return this._needProjectionMatrixCompute}forceProjectionMatrixCompute(){this._needProjectionMatrixCompute=!0}_initCache(){super._initCache(),this._cache.position=B.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=k.Identity()),k.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=H.Vector3[0];let i=this.position;this.computeTransformedInformation()&&(i=this.transformedPosition),B.NormalizeToRef(this.getShadowDirection(e),t),1===Math.abs(B.Dot(t,B.Up()))&&(t.z=1e-13);const n=H.Vector3[1];return i.addToRef(t,n),k.LookAtLHToRef(i,n,B.Up(),this._viewMatrix),this._viewMatrix}getProjectionMatrix(e,t){return this.setShadowProjectionMatrix(this._projectionMatrix,e??this._viewMatrix,t??[]),this._projectionMatrix}}e([h()],Io.prototype,"position",null),e([h()],Io.prototype,"direction",null),e([a()],Io.prototype,"shadowMinZ",null),e([a()],Io.prototype,"shadowMaxZ",null),ae.AddNodeConstructor("Light_Type_1",((e,t)=>()=>new Co(e,B.Zero(),t)));class Co extends Io{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 Xn.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&&k.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 n=this.getScene().activeCamera;if(!n)return;if(this.autoUpdateExtends||this._orthoLeft===Number.MAX_VALUE){const e=B.Zero();this._orthoLeft=Number.MAX_VALUE,this._orthoRight=-Number.MAX_VALUE,this._orthoTop=-Number.MAX_VALUE,this._orthoBottom=Number.MAX_VALUE;let n=Number.MAX_VALUE,r=-Number.MAX_VALUE;for(let s=0;s<i.length;s++){const a=i[s];if(!a)continue;const o=a.getBoundingInfo().boundingBox;for(let i=0;i<o.vectorsWorld.length;i++)B.TransformCoordinatesToRef(o.vectorsWorld[i],t,e),e.x<this._orthoLeft&&(this._orthoLeft=e.x),e.y<this._orthoBottom&&(this._orthoBottom=e.y),e.x>this._orthoRight&&(this._orthoRight=e.x),e.y>this._orthoTop&&(this._orthoTop=e.y),this.autoCalcShadowZBounds&&(e.z<n&&(n=e.z),e.z>r&&(r=e.z))}this.autoCalcShadowZBounds&&(this._shadowMinZ=n,this._shadowMaxZ=r)}const r=this._orthoRight-this._orthoLeft,s=this._orthoTop-this._orthoBottom,a=void 0!==this.shadowMinZ?this.shadowMinZ:n.minZ,o=void 0!==this.shadowMaxZ?this.shadowMaxZ:n.maxZ,l=this.getScene().getEngine().useReverseDepthBuffer;k.OrthoOffCenterLHToRef(this._orthoLeft-r*this.shadowOrthoScale,this._orthoRight+r*this.shadowOrthoScale,this._orthoBottom-s*this.shadowOrthoScale,this._orthoTop+s*this.shadowOrthoScale,l?o:a,l?a:o,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}}e([a()],Co.prototype,"shadowFrustumSize",null),e([a()],Co.prototype,"shadowOrthoScale",null),e([a()],Co.prototype,"autoUpdateExtends",void 0),e([a()],Co.prototype,"autoCalcShadowZBounds",void 0),e([a("orthoLeft")],Co.prototype,"_orthoLeft",void 0),e([a("orthoRight")],Co.prototype,"_orthoRight",void 0),e([a("orthoTop")],Co.prototype,"_orthoTop",void 0),e([a("orthoBottom")],Co.prototype,"_orthoBottom",void 0),M("BABYLON.DirectionalLight",Co),ae.AddNodeConstructor("Light_Type_0",((e,t)=>()=>new Mo(e,B.Zero(),t)));class Mo extends Io{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 Xn.LIGHTTYPEID_POINTLIGHT}needCube(){return!this.direction}getShadowDirection(e){if(this.direction)return super.getShadowDirection(e);switch(e){case 0:return new B(1,0,0);case 1:return new B(-1,0,0);case 2:return new B(0,-1,0);case 3:return new B(0,1,0);case 4:return new B(0,0,1);case 5:return new B(0,0,-1)}return B.Zero()}_setDefaultShadowProjectionMatrix(e,t,i){const n=this.getScene().activeCamera;if(!n)return;const r=void 0!==this.shadowMinZ?this.shadowMinZ:n.minZ,s=void 0!==this.shadowMaxZ?this.shadowMaxZ:n.maxZ,a=this.getScene().getEngine().useReverseDepthBuffer;k.PerspectiveFovLHToRef(this.shadowAngle,1,a?s:r,a?r:s,e,!0,this._scene.getEngine().isNDCHalfZRange,void 0,a)}_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}}e([a()],Mo.prototype,"shadowAngle",null),M("BABYLON.PointLight",Mo),ae.AddNodeConstructor("Light_Type_2",((e,t)=>()=>new xo(e,B.Zero(),B.Zero(),0,0,t)));class xo extends Io{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()&&(xo._IsProceduralTexture(this._projectionTexture)?this._projectionTexture.getEffect().executeWhenCompiled((()=>{this._markMeshesAsLightDirty()})):xo._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,n,r,s){super(e,s),this._innerAngle=0,this._projectionTextureMatrix=k.Zero(),this._projectionTextureLightNear=1e-6,this._projectionTextureLightFar=1e3,this._projectionTextureUpDirection=B.Up(),this._projectionTextureViewLightDirty=!0,this._projectionTextureProjectionLightDirty=!0,this._projectionTextureDirty=!0,this._projectionTextureViewTargetVector=B.Zero(),this._projectionTextureViewLightMatrix=k.Zero(),this._projectionTextureProjectionLightMatrix=k.Zero(),this._projectionTextureScalingMatrix=k.FromValues(.5,0,0,0,0,.5,0,0,0,0,.5,0,.5,.5,.5,1),this.position=t,this.direction=i,this.angle=n,this.exponent=r}getClassName(){return"SpotLight"}getTypeID(){return Xn.LIGHTTYPEID_SPOTLIGHT}_setDirection(e){super._setDirection(e),this._projectionTextureViewLightDirty=!0}_setPosition(e){super._setPosition(e),this._projectionTextureViewLightDirty=!0}_setDefaultShadowProjectionMatrix(e,t,i){const n=this.getScene().activeCamera;if(!n)return;this._shadowAngleScale=this._shadowAngleScale||1;const r=this._shadowAngleScale*this._angle,s=void 0!==this.shadowMinZ?this.shadowMinZ:n.minZ,a=void 0!==this.shadowMaxZ?this.shadowMaxZ:n.maxZ,o=this.getScene().getEngine().useReverseDepthBuffer;k.PerspectiveFovLHToRef(r,1,o?a:s,o?s:a,e,!0,this._scene.getEngine().isNDCHalfZRange,void 0,o)}_computeProjectionTextureViewLightMatrix(){this._projectionTextureViewLightDirty=!1,this._projectionTextureDirty=!0,this.getAbsolutePosition().addToRef(this.getShadowDirection(),this._projectionTextureViewTargetVector),k.LookAtLHToRef(this.getAbsolutePosition(),this._projectionTextureViewTargetVector,this._projectionTextureUpDirection,this._projectionTextureViewLightMatrix)}_computeProjectionTextureProjectionLightMatrix(){this._projectionTextureProjectionLightDirty=!1,this._projectionTextureDirty=!0;const e=this.projectionTextureLightFar,t=this.projectionTextureLightNear,i=e/(e-t),n=-i*t,r=1/Math.tan(this._angle/2);k.FromValuesToRef(r/1,0,0,0,0,r,0,0,0,0,i,1,0,0,n,0,this._projectionTextureProjectionLightMatrix)}_computeProjectionTextureMatrix(){if(this._projectionTextureDirty=!1,this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix,this._projectionTextureMatrix),this._projectionTexture instanceof Pr){const e=this._projectionTexture.uScale/2,t=this._projectionTexture.vScale/2;k.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=B.Normalize(this.transformedDirection)):(this._uniformBuffer.updateFloat4("vLightData",this.position.x,this.position.y,this.position.z,this.exponent,t),i=B.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()?B.Normalize(this.transformedDirection):B.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())}}e([a()],xo.prototype,"angle",null),e([a()],xo.prototype,"innerAngle",null),e([a()],xo.prototype,"shadowAngleScale",null),e([a()],xo.prototype,"exponent",void 0),e([a()],xo.prototype,"projectionTextureLightNear",null),e([a()],xo.prototype,"projectionTextureLightFar",null),e([a()],xo.prototype,"projectionTextureUpDirection",null),e([o("projectedLightTexture")],xo.prototype,"_projectionTexture",void 0),M("BABYLON.SpotLight",xo);const bo="KHR_lights_punctual";class yo{constructor(e){this.name=bo,this._loader=e,this.enabled=this._loader.isExtensionUsed(bo)}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,io.Assign(this._lights)}}loadNodeAsync(e,t,i){return no.LoadExtensionAsync(e,t,this.name,((n,r)=>(this._loader._allMaterialsDirtyRequired=!0,this._loader.loadNodeAsync(e,t,(e=>{let t;const s=io.Get(n,this._lights,r.light),a=s.name||e.name;switch(this._loader.babylonScene._blockEntityCollection=!!this._loader._assetContainer,s.type){case"directional":{const e=new Co(a,B.Backward(),this._loader.babylonScene);e.position.setAll(0),t=e;break}case"point":t=new Mo(a,B.Zero(),this._loader.babylonScene);break;case"spot":{const e=new xo(a,B.Zero(),B.Backward(),0,1,this._loader.babylonScene);e.angle=2*(s.spot&&s.spot.outerConeAngle||Math.PI/4),e.innerAngle=2*(s.spot&&s.spot.innerConeAngle||0),t=e;break}default:throw this._loader.babylonScene._blockEntityCollection=!1,new Error(`${n}: Invalid light type (${s.type})`)}t._parentContainer=this._loader._assetContainer,this._loader.babylonScene._blockEntityCollection=!1,s._babylonLight=t,t.falloffType=Xn.FALLOFF_GLTF,t.diffuse=s.color?ee.FromArray(s.color):ee.White(),t.intensity=null==s.intensity?1:s.intensity,t.range=null==s.range?Number.MAX_VALUE:s.range,t.parent=e,this._loader._babylonLights.push(t),no.AddPointerMetadata(t,n),i(e)})))))}}no.RegisterExtension(bo,(e=>new yo(e)));const Oo="KHR_materials_pbrSpecularGlossiness";class Do{constructor(e){this.name=Oo,this.order=200,this._loader=e,this.enabled=this._loader.isExtensionUsed(Oo)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return no.LoadExtensionAsync(e,t,this.name,((n,r)=>{const s=new Array;return s.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),s.push(this._loadSpecularGlossinessPropertiesAsync(n,r,i)),this._loader.loadMaterialAlphaProperties(e,t,i),Promise.all(s).then((()=>{}))}))}_loadSpecularGlossinessPropertiesAsync(e,t,i){if(!(i instanceof Hs))throw new Error(`${e}: Material type not supported`);const n=new Array;return i.metallic=null,i.roughness=null,t.diffuseFactor?(i.albedoColor=ee.FromArray(t.diffuseFactor),i.alpha=t.diffuseFactor[3]):i.albedoColor=ee.White(),i.reflectivityColor=t.specularFactor?ee.FromArray(t.specularFactor):ee.White(),i.microSurface=null==t.glossinessFactor?1:t.glossinessFactor,t.diffuseTexture&&n.push(this._loader.loadTextureInfoAsync(`${e}/diffuseTexture`,t.diffuseTexture,(e=>{e.name=`${i.name} (Diffuse)`,i.albedoTexture=e}))),t.specularGlossinessTexture&&(n.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(n).then((()=>{}))}}no.RegisterExtension(Oo,(e=>new Do(e)));const No="KHR_materials_unlit";class Po{constructor(e){this.name=No,this.order=210,this._loader=e,this.enabled=this._loader.isExtensionUsed(No)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return no.LoadExtensionAsync(e,t,this.name,(()=>this._loadUnlitPropertiesAsync(e,t,i)))}_loadUnlitPropertiesAsync(e,t,i){if(!(i instanceof Hs))throw new Error(`${e}: Material type not supported`);const n=new Array;i.unlit=!0;const r=t.pbrMetallicRoughness;return r&&(r.baseColorFactor?(i.albedoColor=ee.FromArray(r.baseColorFactor),i.alpha=r.baseColorFactor[3]):i.albedoColor=ee.White(),r.baseColorTexture&&n.push(this._loader.loadTextureInfoAsync(`${e}/baseColorTexture`,r.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(n).then((()=>{}))}}no.RegisterExtension(No,(e=>new Po(e)));const Lo="KHR_materials_clearcoat";class Fo{constructor(e){this.name=Lo,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(Lo)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return no.LoadExtensionAsync(e,t,this.name,((n,r)=>{const s=new Array;return s.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),s.push(this._loadClearCoatPropertiesAsync(n,r,i)),Promise.all(s).then((()=>{}))}))}_loadClearCoatPropertiesAsync(e,t,i){if(!(i instanceof Hs))throw new Error(`${e}: Material type not supported`);const n=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&&n.push(this._loader.loadTextureInfoAsync(`${e}/clearcoatTexture`,t.clearcoatTexture,(e=>{e.name=`${i.name} (ClearCoat Intensity)`,i.clearCoat.texture=e}))),null!=t.clearcoatRoughnessFactor?i.clearCoat.roughness=t.clearcoatRoughnessFactor:i.clearCoat.roughness=0,t.clearcoatRoughnessTexture&&(t.clearcoatRoughnessTexture.nonColorData=!0,n.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,n.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(n).then((()=>{}))}}no.RegisterExtension(Lo,(e=>new Fo(e)));const wo="KHR_materials_iridescence";class Uo{constructor(e){this.name=wo,this.order=195,this._loader=e,this.enabled=this._loader.isExtensionUsed(wo)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return no.LoadExtensionAsync(e,t,this.name,((n,r)=>{const s=new Array;return s.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),s.push(this._loadIridescencePropertiesAsync(n,r,i)),Promise.all(s).then((()=>{}))}))}_loadIridescencePropertiesAsync(e,t,i){if(!(i instanceof Hs))throw new Error(`${e}: Material type not supported`);const n=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&&n.push(this._loader.loadTextureInfoAsync(`${e}/iridescenceTexture`,t.iridescenceTexture,(e=>{e.name=`${i.name} (Iridescence Intensity)`,i.iridescence.texture=e}))),t.iridescenceThicknessTexture&&n.push(this._loader.loadTextureInfoAsync(`${e}/iridescenceThicknessTexture`,t.iridescenceThicknessTexture,(e=>{e.name=`${i.name} (Iridescence Thickness)`,i.iridescence.thicknessTexture=e}))),Promise.all(n).then((()=>{}))}}no.RegisterExtension(wo,(e=>new Uo(e)));const Bo="KHR_materials_anisotropy";class Go{constructor(e){this.name=Bo,this.order=195,this._loader=e,this.enabled=this._loader.isExtensionUsed(Bo)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return no.LoadExtensionAsync(e,t,this.name,((n,r)=>{const s=new Array;return s.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),s.push(this._loadIridescencePropertiesAsync(n,r,i)),Promise.all(s).then((()=>{}))}))}_loadIridescencePropertiesAsync(e,t,i){if(!(i instanceof Hs))throw new Error(`${e}: Material type not supported`);const n=new Array;return i.anisotropy.isEnabled=!0,i.anisotropy.intensity=t.anisotropyStrength??0,i.anisotropy.angle=t.anisotropyRotation??0,t.anisotropyTexture&&n.push(this._loader.loadTextureInfoAsync(`${e}/anisotropyTexture`,t.anisotropyTexture,(e=>{e.name=`${i.name} (Anisotropy Intensity)`,i.anisotropy.texture=e}))),Promise.all(n).then((()=>{}))}}no.RegisterExtension(Bo,(e=>new Go(e)));const Vo="KHR_materials_emissive_strength";class ko{constructor(e){this.name=Vo,this.order=170,this._loader=e,this.enabled=this._loader.isExtensionUsed(Vo)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return no.LoadExtensionAsync(e,t,this.name,((n,r)=>this._loader.loadMaterialPropertiesAsync(e,t,i).then((()=>{this._loadEmissiveProperties(n,r,i)}))))}_loadEmissiveProperties(e,t,i){if(!(i instanceof Hs))throw new Error(`${e}: Material type not supported`);void 0!==t.emissiveStrength&&(i.emissiveIntensity=t.emissiveStrength)}}no.RegisterExtension(Vo,(e=>new ko(e)));const Xo="KHR_materials_sheen";class Ho{constructor(e){this.name=Xo,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(Xo)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return no.LoadExtensionAsync(e,t,this.name,((n,r)=>{const s=new Array;return s.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),s.push(this._loadSheenPropertiesAsync(n,r,i)),Promise.all(s).then((()=>{}))}))}_loadSheenPropertiesAsync(e,t,i){if(!(i instanceof Hs))throw new Error(`${e}: Material type not supported`);const n=new Array;return i.sheen.isEnabled=!0,i.sheen.intensity=1,null!=t.sheenColorFactor?i.sheen.color=ee.FromArray(t.sheenColorFactor):i.sheen.color=ee.Black(),t.sheenColorTexture&&n.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,n.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(n).then((()=>{}))}}no.RegisterExtension(Xo,(e=>new Ho(e)));const Wo="KHR_materials_specular";class zo{constructor(e){this.name=Wo,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(Wo)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return no.LoadExtensionAsync(e,t,this.name,((n,r)=>{const s=new Array;return s.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),s.push(this._loadSpecularPropertiesAsync(n,r,i)),Promise.all(s).then((()=>{}))}))}_loadSpecularPropertiesAsync(e,t,i){if(!(i instanceof Hs))throw new Error(`${e}: Material type not supported`);const n=new Array;return void 0!==t.specularFactor&&(i.metallicF0Factor=t.specularFactor),void 0!==t.specularColorFactor&&(i.metallicReflectanceColor=ee.FromArray(t.specularColorFactor)),t.specularTexture&&(t.specularTexture.nonColorData=!0,n.push(this._loader.loadTextureInfoAsync(`${e}/specularTexture`,t.specularTexture,(e=>{e.name=`${i.name} (Specular F0 Strength)`,i.metallicReflectanceTexture=e,i.useOnlyMetallicFromMetallicReflectanceTexture=!0})))),t.specularColorTexture&&n.push(this._loader.loadTextureInfoAsync(`${e}/specularColorTexture`,t.specularColorTexture,(e=>{e.name=`${i.name} (Specular F0 Color)`,i.reflectanceTexture=e}))),Promise.all(n).then((()=>{}))}}no.RegisterExtension(Wo,(e=>new zo(e)));const Yo="KHR_materials_ior";class Ko{constructor(e){this.name=Yo,this.order=180,this._loader=e,this.enabled=this._loader.isExtensionUsed(Yo)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return no.LoadExtensionAsync(e,t,this.name,((n,r)=>{const s=new Array;return s.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),s.push(this._loadIorPropertiesAsync(n,r,i)),Promise.all(s).then((()=>{}))}))}_loadIorPropertiesAsync(e,t,i){if(!(i instanceof Hs))throw new Error(`${e}: Material type not supported`);return void 0!==t.ior?i.indexOfRefraction=t.ior:i.indexOfRefraction=Ko._DEFAULT_IOR,Promise.resolve()}}Ko._DEFAULT_IOR=1.5,no.RegisterExtension(Yo,(e=>new Ko(e)));const qo="KHR_materials_variants";class jo{constructor(e){this.name=qo,this._loader=e,this.enabled=this._loader.isExtensionUsed(qo)}dispose(){this._loader=null}static GetAvailableVariants(e){const t=this._GetExtensionMetadata(e);return t?Object.keys(t.variants):[]}getAvailableVariants(e){return jo.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 ${qo} extension`);const n=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)n(e);else n(t);i.lastSelected=t}selectVariant(e,t){jo.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 ${qo} extension`);for(const e of t.original)e.mesh.material=e.material;t.lastSelected=null}reset(e){jo.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 ${qo} extension`);return t.lastSelected}getLastSelectedVariant(e){return jo.GetLastSelectedVariant(e)}static _GetExtensionMetadata(e){return e?._internalMetadata?.gltf?.[qo]||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,n,r,s){return no.LoadExtensionAsync(e,r,this.name,((a,o)=>{const l=new Array;return l.push(this._loader._loadMeshPrimitiveAsync(e,t,i,n,r,(t=>{if(s(t),t instanceof ln){const i=no._GetDrawMode(e,r.mode),n=this._loader.rootBabylonMesh,s=n?n._internalMetadata=n._internalMetadata||{}:{},c=s.gltf=s.gltf||{},h=c[qo]=c[qo]||{lastSelected:null,original:[],variants:{}};h.original.push({mesh:t,material:t.material});for(let e=0;e<o.mappings.length;++e){const r=o.mappings[e],s=io.Get(`${a}/mappings/${e}/material`,this._loader.gltf.materials,r.material);l.push(this._loader._loadMaterialAsync(`#/materials/${r.material}`,s,t,i,(e=>{for(let i=0;i<r.variants.length;++i){const s=r.variants[i],a=io.Get(`/extensions/${qo}/variants/${s}`,this._variants,s);h.variants[a.name]=h.variants[a.name]||[],h.variants[a.name].push({mesh:t,material:e}),t.onClonedObservable.add((e=>{const i=e;let r=null,s=i;do{if(s=s.parent,!s)return;r=jo._GetExtensionMetadata(s)}while(null===r);if(n&&r===jo._GetExtensionMetadata(n)){s._internalMetadata={};for(const e in n._internalMetadata)s._internalMetadata[e]=n._internalMetadata[e];s._internalMetadata.gltf=[];for(const e in n._internalMetadata.gltf)s._internalMetadata.gltf[e]=n._internalMetadata.gltf[e];s._internalMetadata.gltf[qo]={lastSelected:null,original:[],variants:{}};for(const e of r.original)s._internalMetadata.gltf[qo].original.push({mesh:e.mesh,material:e.material});for(const e in r.variants)if(Object.prototype.hasOwnProperty.call(r.variants,e)){s._internalMetadata.gltf[qo].variants[e]=[];for(const t of r.variants[e])s._internalMetadata.gltf[qo].variants[e].push({mesh:t.mesh,material:t.material})}r=s._internalMetadata.gltf[qo]}for(const e of r.original)e.mesh===t&&(e.mesh=i);for(const e of r.variants[a.name])e.mesh===t&&(e.mesh=i)}))}})))}}}))),Promise.all(l).then((([e])=>e))}))}}no.RegisterExtension(qo,(e=>new jo(e)));class Qo{static _GetDefaultOptions(){return{renderSize:1024,samples:4,lodGenerationScale:1,lodGenerationOffset:-4,renderTargetTextureType:Ze.TEXTURETYPE_HALF_FLOAT,generateMipmaps:!0}}constructor(e,t){this._opaqueRenderTarget=null,this._opaqueMeshesCache=[],this._transparentMeshesCache=[],this._materialObservers={},this._options={...Qo._GetDefaultOptions(),...e},this._scene=t,this._scene._transmissionHelper=this,this.onErrorObservable=new g,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 Hs&&e.subSurface.isRefractionEnabled)}_addMesh(e){this._materialObservers[e.uniqueId]=e.onMaterialChangedObservable.add(this._onMeshMaterialChanged.bind(this)),Yt.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 Hs&&(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 $r("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 Zo="KHR_materials_transmission";class Jo{constructor(e){this.name=Zo,this.order=175,this._loader=e,this.enabled=this._loader.isExtensionUsed(Zo),this.enabled&&(e.parent.transparencyAsCoverage=!0)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return no.LoadExtensionAsync(e,t,this.name,((n,r)=>{const s=new Array;return s.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),s.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),s.push(this._loadTransparentPropertiesAsync(n,t,i,r)),Promise.all(s).then((()=>{}))}))}_loadTransparentPropertiesAsync(e,t,i,n){if(!(i instanceof Hs))throw new Error(`${e}: Material type not supported`);const r=i;if(r.subSurface.isRefractionEnabled=!0,r.subSurface.volumeIndexOfRefraction=1,r.subSurface.useAlbedoToTintRefraction=!0,void 0===n.transmissionFactor)return r.subSurface.refractionIntensity=0,r.subSurface.isRefractionEnabled=!1,Promise.resolve();{r.subSurface.refractionIntensity=n.transmissionFactor;const e=r.getScene();r.subSurface.refractionIntensity&&!e._transmissionHelper?new Qo({},r.getScene()):r.subSurface.refractionIntensity&&!e._transmissionHelper?._isRenderTargetValid()&&e._transmissionHelper?._setupRenderTargets()}return r.subSurface.minimumThickness=0,r.subSurface.maximumThickness=0,n.transmissionTexture?(n.transmissionTexture.nonColorData=!0,this._loader.loadTextureInfoAsync(`${e}/transmissionTexture`,n.transmissionTexture,void 0).then((e=>{r.subSurface.refractionIntensityTexture=e,r.subSurface.useGltfStyleTextures=!0}))):Promise.resolve()}}no.RegisterExtension(Zo,(e=>new Jo(e)));const $o="KHR_materials_diffuse_transmission";class el{constructor(e){this.name=$o,this.order=174,this._loader=e,this.enabled=this._loader.isExtensionUsed($o),this.enabled&&(e.parent.transparencyAsCoverage=!0)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return no.LoadExtensionAsync(e,t,this.name,((n,r)=>{const s=new Array;return s.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),s.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),s.push(this._loadTranslucentPropertiesAsync(n,t,i,r)),Promise.all(s).then((()=>{}))}))}_loadTranslucentPropertiesAsync(e,t,i,n){if(!(i instanceof Hs))throw new Error(`${e}: Material type not supported`);const r=i;if(r.subSurface.isTranslucencyEnabled=!0,r.subSurface.volumeIndexOfRefraction=1,r.subSurface.minimumThickness=0,r.subSurface.maximumThickness=0,r.subSurface.useAlbedoToTintTranslucency=!1,void 0===n.diffuseTransmissionFactor)return r.subSurface.translucencyIntensity=0,r.subSurface.isTranslucencyEnabled=!1,Promise.resolve();r.subSurface.translucencyIntensity=n.diffuseTransmissionFactor;const s=new Array;return r.subSurface.useGltfStyleTextures=!0,n.diffuseTransmissionTexture&&(n.diffuseTransmissionTexture.nonColorData=!0,s.push(this._loader.loadTextureInfoAsync(`${e}/diffuseTransmissionTexture`,n.diffuseTransmissionTexture).then((e=>{r.subSurface.translucencyIntensityTexture=e})))),void 0!==n.diffuseTransmissionColorFactor?r.subSurface.translucencyColor=ee.FromArray(n.diffuseTransmissionColorFactor):r.subSurface.translucencyColor=ee.White(),n.diffuseTransmissionColorTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/diffuseTransmissionColorTexture`,n.diffuseTransmissionColorTexture).then((e=>{r.subSurface.translucencyColorTexture=e}))),Promise.all(s).then((()=>{}))}}no.RegisterExtension($o,(e=>new el(e)));const tl="KHR_materials_volume";class il{constructor(e){this.name=tl,this.order=173,this._loader=e,this.enabled=this._loader.isExtensionUsed(tl),this.enabled&&this._loader._disableInstancedMesh++}dispose(){this.enabled&&this._loader._disableInstancedMesh--,this._loader=null}loadMaterialPropertiesAsync(e,t,i){return no.LoadExtensionAsync(e,t,this.name,((n,r)=>{const s=new Array;return s.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),s.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),s.push(this._loadVolumePropertiesAsync(n,t,i,r)),Promise.all(s).then((()=>{}))}))}_loadVolumePropertiesAsync(e,t,i,n){if(!(i instanceof Hs))throw new Error(`${e}: Material type not supported`);if(!i.subSurface.isRefractionEnabled&&!i.subSurface.isTranslucencyEnabled||!n.thicknessFactor)return Promise.resolve();i.subSurface.volumeIndexOfRefraction=i.indexOfRefraction;const r=void 0!==n.attenuationDistance?n.attenuationDistance:Number.MAX_VALUE;return i.subSurface.tintColorAtDistance=r,void 0!==n.attenuationColor&&3==n.attenuationColor.length&&i.subSurface.tintColor.copyFromFloats(n.attenuationColor[0],n.attenuationColor[1],n.attenuationColor[2]),i.subSurface.minimumThickness=0,i.subSurface.maximumThickness=n.thicknessFactor,i.subSurface.useThicknessAsDepth=!0,n.thicknessTexture?(n.thicknessTexture.nonColorData=!0,this._loader.loadTextureInfoAsync(`${e}/thicknessTexture`,n.thicknessTexture).then((e=>{i.subSurface.thicknessTexture=e,i.subSurface.useGltfStyleTextures=!0}))):Promise.resolve()}}no.RegisterExtension(tl,(e=>new il(e)));const nl="KHR_materials_dispersion";class rl{constructor(e){this.name=nl,this.order=174,this._loader=e,this.enabled=this._loader.isExtensionUsed(nl)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return no.LoadExtensionAsync(e,t,this.name,((n,r)=>{const s=new Array;return s.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),s.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),s.push(this._loadDispersionPropertiesAsync(n,t,i,r)),Promise.all(s).then((()=>{}))}))}_loadDispersionPropertiesAsync(e,t,i,n){if(!(i instanceof Hs))throw new Error(`${e}: Material type not supported`);return i.subSurface.isRefractionEnabled&&n.dispersion?(i.subSurface.isDispersionEnabled=!0,i.subSurface.dispersion=n.dispersion,Promise.resolve()):Promise.resolve()}}no.RegisterExtension(nl,(e=>new rl(e)));const sl="KHR_mesh_quantization";class al{constructor(e){this.name=sl,this.enabled=e.isExtensionUsed(sl)}dispose(){}}no.RegisterExtension(sl,(e=>new al(e)));const ol="KHR_texture_basisu";class ll{constructor(e){this.name=ol,this._loader=e,this.enabled=e.isExtensionUsed(ol)}dispose(){this._loader=null}_loadTextureAsync(e,t,i){return no.LoadExtensionAsync(e,t,this.name,((n,r)=>{const s=null==t.sampler?no.DefaultSampler:io.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),a=io.Get(`${n}/source`,this._loader.gltf.images,r.source);return this._loader._createTextureAsync(e,s,a,(e=>{i(e)}),t._textureInfo.nonColorData?{useRGBAIfASTCBC7NotAvailableWhenUASTC:!0}:void 0,!t._textureInfo.nonColorData)}))}}no.RegisterExtension(ol,(e=>new ll(e)));const cl="KHR_texture_transform";class hl{constructor(e){this.name=cl,this._loader=e,this.enabled=this._loader.isExtensionUsed(cl)}dispose(){this._loader=null}loadTextureInfoAsync(e,t,i){return no.LoadExtensionAsync(e,t,this.name,((n,r)=>this._loader.loadTextureInfoAsync(e,t,(e=>{if(!(e instanceof Pr))throw new Error(`${n}: Texture type not supported`);r.offset&&(e.uOffset=r.offset[0],e.vOffset=r.offset[1]),e.uRotationCenter=0,e.vRotationCenter=0,r.rotation&&(e.wAng=-r.rotation),r.scale&&(e.uScale=r.scale[0],e.vScale=r.scale[1]),null!=r.texCoord&&(e.coordinatesIndex=r.texCoord),i(e)}))))}}no.RegisterExtension(cl,(e=>new hl(e)));const dl="KHR_xmp_json_ld";class ul{constructor(e){this.name=dl,this.order=100,this._loader=e,this.enabled=this._loader.isExtensionUsed(dl)}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&&i<e.packets.length&&(this._loader.rootBabylonMesh.metadata=this._loader.rootBabylonMesh.metadata||{},this._loader.rootBabylonMesh.metadata.xmp=e.packets[i])}}}function fl(e,t,i,n){return ee.FromArray(t,i).scale(n)}function _l(e,t,i,n){return t[i]*n}function ml(e,t,i,n){return-t[i]*n}function pl(e,t,i,n){return t[i+1]*n}function gl(e,t,i,n){return t[i]*n*2}function El(e){return{scale:[new Al(Cn.ANIMATIONTYPE_FLOAT,`${e}.uScale`,_l,(()=>2)),new Al(Cn.ANIMATIONTYPE_FLOAT,`${e}.vScale`,pl,(()=>2))],offset:[new Al(Cn.ANIMATIONTYPE_FLOAT,`${e}.uOffset`,_l,(()=>2)),new Al(Cn.ANIMATIONTYPE_FLOAT,`${e}.vOffset`,pl,(()=>2))],rotation:[new Al(Cn.ANIMATIONTYPE_FLOAT,`${e}.wAng`,ml,(()=>1))]}}no.RegisterExtension(dl,(e=>new ul(e)));class Tl extends Ja{buildAnimations(e,t,i,n,r){r(e._babylonCamera,this._buildAnimation(t,i,n))}}class Al extends Ja{buildAnimations(e,t,i,n,r){for(const s in e._data)r(e._data[s].babylonMaterial,this._buildAnimation(t,i,n))}}class vl extends Ja{buildAnimations(e,t,i,n,r){r(e._babylonLight,this._buildAnimation(t,i,n))}}const Rl={__array__:{__target__:!0,...eo}},Sl={__array__:{__target__:!0,orthographic:{xmag:[new Tl(Cn.ANIMATIONTYPE_FLOAT,"orthoLeft",ml,(()=>1)),new Tl(Cn.ANIMATIONTYPE_FLOAT,"orthoRight",pl,(()=>1))],ymag:[new Tl(Cn.ANIMATIONTYPE_FLOAT,"orthoBottom",ml,(()=>1)),new Tl(Cn.ANIMATIONTYPE_FLOAT,"orthoTop",pl,(()=>1))],zfar:[new Tl(Cn.ANIMATIONTYPE_FLOAT,"maxZ",_l,(()=>1))],znear:[new Tl(Cn.ANIMATIONTYPE_FLOAT,"minZ",_l,(()=>1))]},perspective:{yfov:[new Tl(Cn.ANIMATIONTYPE_FLOAT,"fov",_l,(()=>1))],zfar:[new Tl(Cn.ANIMATIONTYPE_FLOAT,"maxZ",_l,(()=>1))],znear:[new Tl(Cn.ANIMATIONTYPE_FLOAT,"minZ",_l,(()=>1))]}}},Il={nodes:Rl,materials:{__array__:{__target__:!0,pbrMetallicRoughness:{baseColorFactor:[new Al(Cn.ANIMATIONTYPE_COLOR3,"albedoColor",fl,(()=>4)),new Al(Cn.ANIMATIONTYPE_FLOAT,"alpha",(function(e,t,i,n){return t[i+3]*n}),(()=>4))],metallicFactor:[new Al(Cn.ANIMATIONTYPE_FLOAT,"metallic",_l,(()=>1))],roughnessFactor:[new Al(Cn.ANIMATIONTYPE_FLOAT,"roughness",_l,(()=>1))],baseColorTexture:{extensions:{KHR_texture_transform:El("albedoTexture")}},metallicRoughnessTexture:{extensions:{KHR_texture_transform:El("metallicTexture")}}},emissiveFactor:[new Al(Cn.ANIMATIONTYPE_COLOR3,"emissiveColor",fl,(()=>3))],normalTexture:{scale:[new Al(Cn.ANIMATIONTYPE_FLOAT,"bumpTexture.level",_l,(()=>1))],extensions:{KHR_texture_transform:El("bumpTexture")}},occlusionTexture:{strength:[new Al(Cn.ANIMATIONTYPE_FLOAT,"ambientTextureStrength",_l,(()=>1))],extensions:{KHR_texture_transform:El("ambientTexture")}},emissiveTexture:{extensions:{KHR_texture_transform:El("emissiveTexture")}},extensions:{KHR_materials_anisotropy:{anisotropyStrength:[new Al(Cn.ANIMATIONTYPE_FLOAT,"anisotropy.intensity",_l,(()=>1))],anisotropyRotation:[new Al(Cn.ANIMATIONTYPE_FLOAT,"anisotropy.angle",_l,(()=>1))],anisotropyTexture:{extensions:{KHR_texture_transform:El("anisotropy.texture")}}},KHR_materials_clearcoat:{clearcoatFactor:[new Al(Cn.ANIMATIONTYPE_FLOAT,"clearCoat.intensity",_l,(()=>1))],clearcoatRoughnessFactor:[new Al(Cn.ANIMATIONTYPE_FLOAT,"clearCoat.roughness",_l,(()=>1))],clearcoatTexture:{extensions:{KHR_texture_transform:El("clearCoat.texture")}},clearcoatNormalTexture:{scale:[new Al(Cn.ANIMATIONTYPE_FLOAT,"clearCoat.bumpTexture.level",_l,(()=>1))],extensions:{KHR_texture_transform:El("clearCoat.bumpTexture")}},clearcoatRoughnessTexture:{extensions:{KHR_texture_transform:El("clearCoat.textureRoughness")}}},KHR_materials_dispersion:{dispersion:[new Al(Cn.ANIMATIONTYPE_FLOAT,"subSurface.dispersion",_l,(()=>1))]},KHR_materials_emissive_strength:{emissiveStrength:[new Al(Cn.ANIMATIONTYPE_FLOAT,"emissiveIntensity",_l,(()=>1))]},KHR_materials_ior:{ior:[new Al(Cn.ANIMATIONTYPE_FLOAT,"indexOfRefraction",_l,(()=>1))]},KHR_materials_iridescence:{iridescenceFactor:[new Al(Cn.ANIMATIONTYPE_FLOAT,"iridescence.intensity",_l,(()=>1))],iridescenceIor:[new Al(Cn.ANIMATIONTYPE_FLOAT,"iridescence.indexOfRefraction",_l,(()=>1))],iridescenceThicknessMinimum:[new Al(Cn.ANIMATIONTYPE_FLOAT,"iridescence.minimumThickness",_l,(()=>1))],iridescenceThicknessMaximum:[new Al(Cn.ANIMATIONTYPE_FLOAT,"iridescence.maximumThickness",_l,(()=>1))],iridescenceTexture:{extensions:{KHR_texture_transform:El("iridescence.texture")}},iridescenceThicknessTexture:{extensions:{KHR_texture_transform:El("iridescence.thicknessTexture")}}},KHR_materials_sheen:{sheenColorFactor:[new Al(Cn.ANIMATIONTYPE_COLOR3,"sheen.color",fl,(()=>3))],sheenRoughnessFactor:[new Al(Cn.ANIMATIONTYPE_FLOAT,"sheen.roughness",_l,(()=>1))],sheenColorTexture:{extensions:{KHR_texture_transform:El("sheen.texture")}},sheenRoughnessTexture:{extensions:{KHR_texture_transform:El("sheen.textureRoughness")}}},KHR_materials_specular:{specularFactor:[new Al(Cn.ANIMATIONTYPE_FLOAT,"metallicF0Factor",_l,(()=>1))],specularColorFactor:[new Al(Cn.ANIMATIONTYPE_COLOR3,"metallicReflectanceColor",fl,(()=>3))],specularTexture:{extensions:{KHR_texture_transform:El("metallicReflectanceTexture")}},specularColorTexture:{extensions:{KHR_texture_transform:El("reflectanceTexture")}}},KHR_materials_transmission:{transmissionFactor:[new Al(Cn.ANIMATIONTYPE_FLOAT,"subSurface.refractionIntensity",_l,(()=>1))],transmissionTexture:{extensions:{KHR_texture_transform:El("subSurface.refractionIntensityTexture")}}},KHR_materials_volume:{attenuationColor:[new Al(Cn.ANIMATIONTYPE_COLOR3,"subSurface.tintColor",fl,(()=>3))],attenuationDistance:[new Al(Cn.ANIMATIONTYPE_FLOAT,"subSurface.tintColorAtDistance",_l,(()=>1))],thicknessFactor:[new Al(Cn.ANIMATIONTYPE_FLOAT,"subSurface.maximumThickness",_l,(()=>1))],thicknessTexture:{extensions:{KHR_texture_transform:El("subSurface.thicknessTexture")}}},KHR_materials_diffuse_transmission:{diffuseTransmissionFactor:[new Al(Cn.ANIMATIONTYPE_FLOAT,"subSurface.translucencyIntensity",_l,(()=>1))],diffuseTransmissionTexture:{extensions:{KHR_texture_transform:El("subSurface.translucencyIntensityTexture")}},diffuseTransmissionColorFactor:[new Al(Cn.ANIMATIONTYPE_COLOR3,"subSurface.translucencyColor",fl,(()=>3))],diffuseTransmissionColorTexture:{extensions:{KHR_texture_transform:El("subSurface.translucencyColorTexture")}}}}}},cameras:Sl,extensions:{KHR_lights_punctual:{lights:{__array__:{__target__:!0,color:[new vl(Cn.ANIMATIONTYPE_COLOR3,"diffuse",fl,(()=>3))],intensity:[new vl(Cn.ANIMATIONTYPE_FLOAT,"intensity",_l,(()=>1))],range:[new vl(Cn.ANIMATIONTYPE_FLOAT,"range",_l,(()=>1))],spot:{innerConeAngle:[new vl(Cn.ANIMATIONTYPE_FLOAT,"innerAngle",gl,(()=>1))],outerConeAngle:[new vl(Cn.ANIMATIONTYPE_FLOAT,"angle",gl,(()=>1))]}}}}}};class Cl{constructor(e,t){this._gltf=e,this._infoTree=t}convert(e){let t,i=this._gltf,n=this._infoTree;if(!e.startsWith("/"))throw new Error("Path must start with a /");const r=e.split("/");r.shift();for(const s of r){if(n.__array__)n=n.__array__;else if(n=n[s],!n)throw new Error(`Path ${e} is invalid`);if(void 0===i)throw new Error(`Path ${e} is invalid`);i=i[s],n.__target__&&(t=i)}return{object:t,info:n}}}const Ml="KHR_animation_pointer";class xl extends Cl{constructor(e){super(e,Il)}}class bl{constructor(e){this.name=Ml,this._loader=e,this._pathToObjectConverter=new xl(this._loader.gltf)}get enabled(){return this._loader.isExtensionUsed(Ml)}dispose(){this._loader=null,delete this._pathToObjectConverter}_loadAnimationChannelAsync(e,t,i,n,r){const s=n.target.extensions?.KHR_animation_pointer;if(!s||!this._pathToObjectConverter)return null;"pointer"!==n.target.path&&de.Warn(`${e}/target/path: Value (${n.target.path}) must be (pointer) when using the ${this.name} extension`),null!=n.target.node&&de.Warn(`${e}/target/node: Value (${n.target.node}) must not be present when using the ${this.name} extension`);const a=`${e}/extensions/${this.name}`,o=s.pointer;if(!o)throw new Error(`${a}: Pointer is missing`);try{const s=this._pathToObjectConverter.convert(o);return this._loader._loadAnimationChannelFromTargetInfoAsync(e,t,i,n,s,r)}catch(e){return de.Warn(`${a}/pointer: Invalid pointer (${o}) skipped`),null}}}no.RegisterExtension(Ml,(e=>new bl(e)));class yl{constructor(e,t,i){this.frame=e,this.action=t,this.onlyOnce=i,this.isDone=!1}_clone(){return new yl(this.frame,this.action,this.onlyOnce)}}class Ol{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(vt.audioEngine?.audioContext&&(this.isPlaying||this.isPaused)){const e=this.isPaused?0:vt.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,n=null,r){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 g,this._spatialSound=!1,this._panningModel="equalpower",this._playbackRate=1,this._streaming=!1,this._startTime=0,this._currentTime=0,this._position=B.Zero(),this._localDirection=new B(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||y.LastCreatedScene)if(this._scene=i,Ol._SceneComponentInitialization(i),this._readyToPlayCallback=n,this._customAttenuationFunction=(e,t,i,n,r)=>t<i?e*(1-t/i):0,r&&(this.autoplay=r.autoplay||!1,this._loop=r.loop||!1,void 0!==r.volume&&(this._volume=r.volume),this._spatialSound=r.spatialSound??!1,this.maxDistance=r.maxDistance??100,this.useCustomAttenuation=r.useCustomAttenuation??!1,this.rolloffFactor=r.rolloffFactor||1,this.refDistance=r.refDistance||1,this.distanceModel=r.distanceModel||"linear",this._playbackRate=r.playbackRate||1,this._streaming=r.streaming??!1,this._length=r.length,this._offset=r.offset),vt.audioEngine?.canUseWebAudio&&vt.audioEngine.audioContext){this._soundGain=vt.audioEngine.audioContext.createGain(),this._soundGain.gain.value=this._volume,this._inputAudioNode=this._soundGain,this._outputAudioNode=this._soundGain,this._spatialSound&&this._createSpatialParameters(),this._scene.mainSoundTrack.addSound(this);let e=!0;if(t)try{"string"==typeof t?(this._urlType="String",this._url=t):t instanceof ArrayBuffer?this._urlType="ArrayBuffer":t instanceof HTMLMediaElement?this._urlType="MediaElement":t instanceof MediaStream?this._urlType="MediaStream":t instanceof AudioBuffer?this._urlType="AudioBuffer":Array.isArray(t)&&(this._urlType="Array");let i=[],n=!1;switch(this._urlType){case"MediaElement":this._streaming=!0,this._isReadyToPlay=!0,this._streamingSource=vt.audioEngine.audioContext.createMediaElementSource(t),this.autoplay&&this.play(0,this._offset,this._length),this._readyToPlayCallback&&this._readyToPlayCallback();break;case"MediaStream":this._streaming=!0,this._isReadyToPlay=!0,this._streamingSource=vt.audioEngine.audioContext.createMediaStreamSource(t),this.autoplay&&this.play(0,this._offset,this._length),this._readyToPlayCallback&&this._readyToPlayCallback();break;case"ArrayBuffer":t.byteLength>0&&(n=!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<i.length;e++){const t=i[e];if(n=r&&r.skipCodecCheck||-1!==t.indexOf(".mp3",t.length-4)&&vt.audioEngine.isMP3supported||-1!==t.indexOf(".ogg",t.length-4)&&vt.audioEngine.isOGGsupported||-1!==t.indexOf(".wav",t.length-4)||-1!==t.indexOf(".m4a",t.length-4)||-1!==t.indexOf(".mp4",t.length-4)||-1!==t.indexOf("blob:"),n){this._streaming?(this._htmlAudioElement=new Audio(t),this._htmlAudioElement.controls=!1,this._htmlAudioElement.loop=this.loop,Yt.SetCorsBehavior(t,this._htmlAudioElement),this._htmlAudioElement.preload="auto",this._htmlAudioElement.addEventListener("canplaythrough",(()=>{this._isReadyToPlay=!0,this.autoplay&&this.play(0,this._offset,this._length),this._readyToPlayCallback&&this._readyToPlayCallback()})),document.body.appendChild(this._htmlAudioElement),this._htmlAudioElement.load()):this._scene._loadFile(t,(e=>{this._soundLoaded(e)}),void 0,!0,!0,(e=>{e&&de.Error("XHR "+e.status+" error on: "+t+"."),de.Error("Sound creation aborted."),this._scene.mainSoundTrack.removeSound(this)}));break}}break;default:e=!1}e?n||(this._isReadyToPlay=!0,this._readyToPlayCallback&&setTimeout((()=>{this._readyToPlayCallback&&this._readyToPlayCallback()}),1e3)):de.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.")}catch(e){de.Error("Unexpected error. Sound creation aborted."),this._scene.mainSoundTrack.removeSound(this)}}else this._scene.mainSoundTrack.addSound(this),vt.audioEngine&&!vt.audioEngine.WarnedWebAudioUnsupported&&(de.Error("Web Audio is not supported by your browser."),vt.audioEngine.WarnedWebAudioUnsupported=!0),this._readyToPlayCallback&&setTimeout((()=>{this._readyToPlayCallback&&this._readyToPlayCallback()}),1e3)}dispose(){vt.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._streamingSource&&this._streamingSource.disconnect(),this._connectedTransformNode&&this._registerFunc&&(this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._connectedTransformNode=null),this._clearTimeoutsAndObservers())}isReady(){return this._isReadyToPlay}getClassName(){return"Sound"}_audioBufferLoaded(e){vt.audioEngine?.audioContext&&(this._audioBuffer=e,this._isReadyToPlay=!0,this.autoplay&&this.play(0,this._offset,this._length),this._readyToPlayCallback&&this._readyToPlayCallback())}_soundLoaded(e){vt.audioEngine?.audioContext&&vt.audioEngine.audioContext.decodeAudioData(e,(e=>{this._audioBufferLoaded(e)}),(e=>{de.Error("Error while decoding audio data for: "+this.name+" / Error: "+e)}))}setAudioBuffer(e){vt.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(){vt.audioEngine?.canUseWebAudio&&vt.audioEngine.audioContext&&(this._scene.headphone&&(this._panningModel="HRTF"),this._soundPanner=this._soundPanner??vt.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(){vt.audioEngine?.canUseWebAudio&&this._spatialSound&&this._soundPanner&&(this._soundPanner.panningModel=this._panningModel)}connectToSoundTrackAudioNode(e){vt.audioEngine?.canUseWebAudio&&this._outputAudioNode&&(this._isOutputConnected&&this._outputAudioNode.disconnect(),this._outputAudioNode.connect(e),this._isOutputConnected=!0)}setDirectionalCone(e,t,i){t<e?de.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle."):(this._coneInnerAngle=e,this._coneOuterAngle=t,this._coneOuterGain=i,this._isDirectional=!0,this.isPlaying&&this.loop&&(this.stop(),this.play(0,this._offset,this._length)))}get directionalConeInnerAngle(){return this._coneInnerAngle}set directionalConeInnerAngle(e){if(e!=this._coneInnerAngle){if(this._coneOuterAngle<e)return void de.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");this._coneInnerAngle=e,vt.audioEngine?.canUseWebAudio&&this._spatialSound&&this._soundPanner&&(this._soundPanner.coneInnerAngle=this._coneInnerAngle)}}get directionalConeOuterAngle(){return this._coneOuterAngle}set directionalConeOuterAngle(e){if(e!=this._coneOuterAngle){if(e<this._coneInnerAngle)return void de.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");this._coneOuterAngle=e,vt.audioEngine?.canUseWebAudio&&this._spatialSound&&this._soundPanner&&(this._soundPanner.coneOuterAngle=this._coneOuterAngle)}}setPosition(e){e.equals(this._position)||(this._position.copyFrom(e),vt.audioEngine?.canUseWebAudio&&this._spatialSound&&this._soundPanner&&!isNaN(this._position.x)&&!isNaN(this._position.y)&&!isNaN(this._position.z)&&(this._soundPanner.positionX.value=this._position.x,this._soundPanner.positionY.value=this._position.y,this._soundPanner.positionZ.value=this._position.z))}setLocalDirectionToMesh(e){this._localDirection=e,vt.audioEngine?.canUseWebAudio&&this._connectedTransformNode&&this.isPlaying&&this._updateDirection()}_updateDirection(){if(!this._connectedTransformNode||!this._soundPanner)return;const e=this._connectedTransformNode.getWorldMatrix(),t=B.TransformNormal(this._localDirection,e);t.normalize(),this._soundPanner.orientationX.value=t.x,this._soundPanner.orientationY.value=t.y,this._soundPanner.orientationZ.value=t.z}updateDistanceFromListener(){if(vt.audioEngine?.canUseWebAudio&&this._connectedTransformNode&&this.useCustomAttenuation&&this._soundGain&&this._scene.activeCamera){const e=this._scene.audioListenerPositionProvider?this._connectedTransformNode.position.subtract(this._scene.audioListenerPositionProvider()).length():this._connectedTransformNode.getDistanceToCamera(this._scene.activeCamera);this._soundGain.gain.value=this._customAttenuationFunction(this._volume,e,this.maxDistance,this.refDistance,this.rolloffFactor)}}setAttenuationFunction(e){this._customAttenuationFunction=e}play(e,t,i){if(this._isReadyToPlay&&this._scene.audioEnabled&&vt.audioEngine?.audioContext)try{this._clearTimeoutsAndObservers();let n=e?vt.audioEngine?.audioContext.currentTime+e:vt.audioEngine?.audioContext.currentTime;if(this._soundSource&&this._streamingSource||this._spatialSound&&this._soundPanner&&(isNaN(this._position.x)||isNaN(this._position.y)||isNaN(this._position.z)||(this._soundPanner.positionX.value=this._position.x,this._soundPanner.positionY.value=this._position.y,this._soundPanner.positionZ.value=this._position.z),this._isDirectional&&(this._soundPanner.coneInnerAngle=this._coneInnerAngle,this._soundPanner.coneOuterAngle=this._coneOuterAngle,this._soundPanner.coneOuterGain=this._coneOuterGain,this._connectedTransformNode?this._updateDirection():this._soundPanner.setOrientation(this._localDirection.x,this._localDirection.y,this._localDirection.z))),this._streaming){if(this._streamingSource||(this._streamingSource=vt.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement),this._htmlAudioElement.onended=()=>{this._onended()},this._htmlAudioElement.playbackRate=this._playbackRate),this._streamingSource.disconnect(),this._inputAudioNode&&this._streamingSource.connect(this._inputAudioNode),this._htmlAudioElement){const e=()=>{if(vt.audioEngine?.unlocked){const t=this._htmlAudioElement.play();void 0!==t&&t.catch((()=>{vt.audioEngine?.lock(),(this.loop||this.autoplay)&&(this._audioUnlockedObserver=vt.audioEngine?.onAudioUnlockedObservable.addOnce((()=>{e()})))}))}else(this.loop||this.autoplay)&&(this._audioUnlockedObserver=vt.audioEngine?.onAudioUnlockedObservable.addOnce((()=>{e()})))};e()}}else{const r=()=>{if(vt.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=vt.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()},n=e?vt.audioEngine?.audioContext.currentTime+e:vt.audioEngine.audioContext.currentTime;const r=((this.isPaused?this.currentTime:0)+(this._offset??0))%this._soundSource.buffer.duration;this._soundSource.start(n,r,this.loop?void 0:i)}}};"suspended"===vt.audioEngine?.audioContext.state?this._tryToPlayTimeout=setTimeout((()=>{"suspended"===vt.audioEngine?.audioContext.state?(vt.audioEngine.lock(),(this.loop||this.autoplay)&&(this._audioUnlockedObserver=vt.audioEngine.onAudioUnlockedObservable.addOnce((()=>{r()})))):r()}),500):r()}this._startTime=n,this.isPlaying=!0,this.isPaused=!1}catch(e){de.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(vt.audioEngine?.audioContext&&this._soundSource){const t=e?vt.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):vt.audioEngine?.audioContext&&this._soundSource&&(this._soundSource.onended=()=>{},this._soundSource.stop(),this.isPlaying=!1,this.isPaused=!0,this._currentTime+=vt.audioEngine.audioContext.currentTime-this._startTime))}setVolume(e,t){vt.audioEngine?.canUseWebAudio&&this._soundGain&&(t&&vt.audioEngine.audioContext?(this._soundGain.gain.cancelScheduledValues(vt.audioEngine.audioContext.currentTime),this._soundGain.gain.setValueAtTime(this._soundGain.gain.value,vt.audioEngine.audioContext.currentTime),this._soundGain.gain.linearRampToValueAtTime(e,vt.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);vt.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 Ol(this.name+"_cloned",new ArrayBuffer(0),this._scene,null,t);return this.useCustomAttenuation&&i.setAttenuationFunction(this._customAttenuationFunction),i.setPosition(this._position),i.setPlaybackRate(this._playbackRate),e(),i}}getAudioBuffer(){return this._audioBuffer}getSoundSource(){return this._soundSource}getSoundGain(){return this._soundGain}serialize(){const e={name:this.name,url:this._url,autoplay:this.autoplay,loop:this.loop,volume:this._volume,spatialSound:this._spatialSound,maxDistance:this.maxDistance,rolloffFactor:this.rolloffFactor,refDistance:this.refDistance,distanceModel:this.distanceModel,playbackRate:this._playbackRate,panningModel:this._panningModel,soundTrackId:this.soundTrackId,metadata:this.metadata};return this._spatialSound&&(this._connectedTransformNode&&(e.connectedMeshId=this._connectedTransformNode.id),e.position=this._position.asArray(),e.refDistance=this.refDistance,e.distanceModel=this.distanceModel,e.isDirectional=this._isDirectional,e.localDirectionToMesh=this._localDirection.asArray(),e.coneInnerAngle=this._coneInnerAngle,e.coneOuterAngle=this._coneOuterAngle,e.coneOuterGain=this._coneOuterGain),e}static Parse(e,t,i,n){const r=e.name;let s;s=e.url?i+e.url:i+r;const a={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 o;if(n){const e=()=>{n._isReadyToPlay?(o._audioBuffer=n.getAudioBuffer(),o._isReadyToPlay=!0,o.autoplay&&o.play(0,o._offset,o._length)):setTimeout(e,300)};o=new Ol(r,new ArrayBuffer(0),t,null,a),e()}else o=new Ol(r,s,t,(()=>{t.removePendingData(o)}),a),t.addPendingData(o);if(e.position){const t=B.FromArray(e.position);o.setPosition(t)}if(e.isDirectional&&(o.setDirectionalCone(e.coneInnerAngle||360,e.coneOuterAngle||360,e.coneOuterGain||0),e.localDirectionToMesh)){const t=B.FromArray(e.localDirectionToMesh);o.setLocalDirectionToMesh(t)}if(e.connectedMeshId){const i=t.getMeshById(e.connectedMeshId);i&&o.attachToMesh(i)}return e.metadata&&(o.metadata=e.metadata),o}_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&&(vt.audioEngine?.onAudioUnlockedObservable.remove(this._audioUnlockedObserver),this._audioUnlockedObserver=null)}}Ol._SceneComponentInitialization=e=>{throw Y("AudioSceneComponent")},M("BABYLON.Sound",Ol);class Dl{constructor(e,t,i){if(this.loop=!1,this._coneInnerAngle=360,this._coneOuterAngle=360,this._volume=1,this.isPlaying=!1,this.isPaused=!1,this._sounds=[],this._weights=[],t.length!==i.length)throw new Error("Sounds length does not equal weights length");this.loop=e,this._weights=i;let n=0;for(const e of i)n+=e;const r=n>0?1/n:0;for(let e=0;e<this._weights.length;e++)this._weights[e]*=r;this._sounds=t;for(const e of this._sounds)e.onEndedObservable.add((()=>{this._onended()}))}get directionalConeInnerAngle(){return this._coneInnerAngle}set directionalConeInnerAngle(e){if(e!==this._coneInnerAngle){if(this._coneOuterAngle<e)return void de.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");this._coneInnerAngle=e;for(const t of this._sounds)t.directionalConeInnerAngle=e}}get directionalConeOuterAngle(){return this._coneOuterAngle}set directionalConeOuterAngle(e){if(e!==this._coneOuterAngle){if(e<this._coneInnerAngle)return void de.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");this._coneOuterAngle=e;for(const t of this._sounds)t.directionalConeOuterAngle=e}}get volume(){return this._volume}set volume(e){if(e!==this._volume)for(const t of this._sounds)t.setVolume(e)}_onended(){void 0!==this._currentIndex&&(this._sounds[this._currentIndex].autoplay=!1),this.loop&&this.isPlaying?this.play():this.isPlaying=!1}pause(){this.isPaused=!0,void 0!==this._currentIndex&&this._sounds[this._currentIndex].pause()}stop(){this.isPlaying=!1,void 0!==this._currentIndex&&this._sounds[this._currentIndex].stop()}play(e){if(!this.isPaused){this.stop();const e=Math.random();let t=0;for(let i=0;i<this._weights.length;i++)if(t+=this._weights[i],e<=t){this._currentIndex=i;break}}const t=this._sounds[this._currentIndex];t.isReady()?t.play(0,this.isPaused?void 0:e):t.autoplay=!0,this.isPlaying=!0,this.isPaused=!1}}const Nl="MSFT_audio_emitter";class Pl{constructor(e){this.name=Nl,this._loader=e,this.enabled=this._loader.isExtensionUsed(Nl)}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,io.Assign(this._clips),io.Assign(this._emitters)}}loadSceneAsync(e,t){return no.LoadExtensionAsync(e,t,this.name,((i,n)=>{const r=new Array;r.push(this._loader.loadSceneAsync(e,t));for(const e of n.emitters){const t=io.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`);r.push(this._loadEmitterAsync(`${i}/emitters/${t.index}`,t))}return Promise.all(r).then((()=>{}))}))}loadNodeAsync(e,t,i){return no.LoadExtensionAsync(e,t,this.name,((e,n)=>{const r=new Array;return this._loader.loadNodeAsync(e,t,(t=>{for(const i of n.emitters){const n=io.Get(`${e}/emitters`,this._emitters,i);r.push(this._loadEmitterAsync(`${e}/emitters/${n.index}`,n).then((()=>{for(const e of n._babylonSounds)e.attachToMesh(t),null==n.innerAngle&&null==n.outerAngle||(e.setLocalDirectionToMesh(B.Forward()),e.setDirectionalCone(2*Yt.ToDegrees(null==n.innerAngle?Math.PI:n.innerAngle),2*Yt.ToDegrees(null==n.outerAngle?Math.PI:n.outerAngle),0))})))}i(t)})).then((e=>Promise.all(r).then((()=>e))))}))}loadAnimationAsync(e,t){return no.LoadExtensionAsync(e,t,this.name,((i,n)=>this._loader.loadAnimationAsync(e,t).then((r=>{const s=new Array;io.Assign(n.events);for(const a of n.events)s.push(this._loadAnimationEventAsync(`${i}/events/${a.index}`,e,t,a,r));return Promise.all(s).then((()=>r))}))))}_loadClipAsync(e,t){if(t._objectURL)return t._objectURL;let i;if(t.uri)i=this._loader.loadUriAsync(e,t,t.uri);else{const n=io.Get(`${e}/bufferView`,this._loader.gltf.bufferViews,t.bufferView);i=this._loader.loadBufferViewAsync(`/bufferViews/${n.index}`,n)}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}`,n={loop:!1,autoplay:!1,volume:null==t.volume?1:t.volume};for(let r=0;r<t.clips.length;r++){const s=`/extensions/${this.name}/clips`,a=io.Get(s,this._clips,t.clips[r].clip);e.push(this._loadClipAsync(`${s}/${t.clips[r].clip}`,a).then((e=>{const s=t._babylonSounds[r]=new Ol(i,e,this._loader.babylonScene,null,n);s.refDistance=t.refDistance||1,s.maxDistance=t.maxDistance||256,s.rolloffFactor=t.rolloffFactor||1,s.distanceModel=t.distanceModel||"exponential"})))}const r=Promise.all(e).then((()=>{const e=t.clips.map((e=>e.weight||1)),i=new Dl(t.loop||!1,t._babylonSounds,e);t.innerAngle&&(i.directionalConeInnerAngle=2*Yt.ToDegrees(t.innerAngle)),t.outerAngle&&(i.directionalConeOuterAngle=2*Yt.ToDegrees(t.outerAngle)),t.volume&&(i.volume=t.volume),t._babylonData.sound=i}));t._babylonData={loaded:r}}return t._babylonData.loaded}_getEventAction(e,t,i,n,r){switch(i){case"play":return e=>{const i=(r||0)+(e-n);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,n,r){if(0==r.targetedAnimations.length)return Promise.resolve();const s=r.targetedAnimations[0],a=n.emitter,o=io.Get(`/extensions/${this.name}/emitters`,this._emitters,a);return this._loadEmitterAsync(e,o).then((()=>{const t=o._babylonData.sound;if(t){const i=new yl(n.time,this._getEventAction(e,t,n.action,n.time,n.startOffset));s.animation.addEvent(i),r.onAnimationGroupEndObservable.add((()=>{t.stop()})),r.onAnimationGroupPauseObservable.add((()=>{t.pause()}))}}))}}no.RegisterExtension(Nl,(e=>new Pl(e)));const Ll="MSFT_lod";class Fl{constructor(e){this.name=Ll,this.order=100,this.maxLODsToLoad=10,this.onNodeLODsLoadedObservable=new g,this.onMaterialLODsLoadedObservable=new g,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[Ll]?.maxLODsToLoad??this.maxLODsToLoad,this.enabled=this._loader.isExtensionUsed(Ll)}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<this._nodePromiseLODs.length;e++){const t=Promise.all(this._nodePromiseLODs[e]).then((()=>{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<this._materialPromiseLODs.length;e++){const t=Promise.all(this._materialPromiseLODs[e]).then((()=>{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 no.LoadExtensionAsync(e,t,this.name,((e,n)=>{let r;const s=this._getLODs(e,t,this._loader.gltf.nodes,n.ids);this._loader.logOpen(`${e}`);for(let e=0;e<s.length;e++){const t=s[e];0!==e&&(this._nodeIndexLOD=e,this._nodeSignalLODs[e]=this._nodeSignalLODs[e]||new sa);const n=e=>{i(e),e.setEnabled(!1)},a=this._loader.loadNodeAsync(`/nodes/${t.index}`,t,n).then((t=>{if(0!==e){const t=s[e-1];t._babylonTransformNode&&(this._disposeTransformNode(t._babylonTransformNode),delete t._babylonTransformNode)}return t.setEnabled(!0),t}));this._nodePromiseLODs[e]=this._nodePromiseLODs[e]||[],0===e?r=a:(this._nodeIndexLOD=null,this._nodePromiseLODs[e].push(a))}return this._loader.logClose(),r}))}_loadMaterialAsync(e,t,i,n,r){return this._nodeIndexLOD?null:no.LoadExtensionAsync(e,t,this.name,((e,s)=>{let a;const o=this._getLODs(e,t,this._loader.gltf.materials,s.ids);this._loader.logOpen(`${e}`);for(let e=0;e<o.length;e++){const t=o[e];0!==e&&(this._materialIndexLOD=e);const s=this._loader._loadMaterialAsync(`/materials/${t.index}`,t,i,n,(t=>{0===e&&r(t)})).then((t=>{if(0!==e){r(t);const i=o[e-1]._data;i[n]&&(this._disposeMaterials([i[n].babylonMaterial]),delete i[n])}return t}));this._materialPromiseLODs[e]=this._materialPromiseLODs[e]||[],0===e?a=s:(this._materialIndexLOD=null,this._materialPromiseLODs[e].push(s))}return this._loader.logClose(),a}))}_loadUriAsync(e,t,i){if(null!==this._nodeIndexLOD){this._loader.log("deferred");const n=this._nodeIndexLOD-1;return this._nodeSignalLODs[n]=this._nodeSignalLODs[n]||new sa,this._nodeSignalLODs[this._nodeIndexLOD-1].promise.then((()=>this._loader.loadUriAsync(e,t,i)))}if(null!==this._materialIndexLOD){this._loader.log("deferred");const n=this._materialIndexLOD-1;return this._materialSignalLODs[n]=this._materialSignalLODs[n]||new sa,this._materialSignalLODs[n].promise.then((()=>this._loader.loadUriAsync(e,t,i)))}return null}loadBufferAsync(e,t,i,n){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 r=i,s=r+n-1;let a=e[t];return a?(a.start=Math.min(a.start,r),a.end=Math.max(a.end,s)):(a={start:r,end:s,loaded:new sa},e[t]=a),a.loaded.promise.then((e=>new Uint8Array(e.buffer,e.byteOffset+i-a.start,n)))};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,n){if(this.maxLODsToLoad<=0)throw new Error("maxLODsToLoad must be greater than zero");const r=[];for(let t=n.length-1;t>=0;t--)if(r.push(io.Get(`${e}/ids/${n[t]}`,i,n[t])),r.length===this.maxLODsToLoad)return r;return r.push(t),r}_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 n=t.filter((e=>this._loader.babylonScene.meshes.every((t=>t.material!=e))));this._disposeMaterials(n)}_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()}}no.RegisterExtension(Ll,(e=>new Fl(e)));const wl="MSFT_minecraftMesh";class Ul{constructor(e){this.name=wl,this._loader=e,this.enabled=this._loader.isExtensionUsed(wl)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return no.LoadExtraAsync(e,t,this.name,((n,r)=>{if(r){if(!(i instanceof Hs))throw new Error(`${n}: Material type not supported`);const r=this._loader.loadMaterialPropertiesAsync(e,t,i);return i.needAlphaBlending()&&(i.forceDepthWrite=!0,i.separateCullingPass=!0),i.backFaceCulling=i.forceDepthWrite,i.twoSidedLighting=!0,r}return null}))}}no.RegisterExtension(wl,(e=>new Ul(e)));const Bl="MSFT_sRGBFactors";class Gl{constructor(e){this.name=Bl,this._loader=e,this.enabled=this._loader.isExtensionUsed(Bl)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return no.LoadExtraAsync(e,t,this.name,((n,r)=>{if(r){if(!(i instanceof Hs))throw new Error(`${n}: Material type not supported`);const r=this._loader.loadMaterialPropertiesAsync(e,t,i),s=i.getScene().getEngine().useExactSrgbConversions;return i.albedoTexture||i.albedoColor.toLinearSpaceToRef(i.albedoColor,s),i.reflectivityTexture||i.reflectivityColor.toLinearSpaceToRef(i.reflectivityColor,s),r}return null}))}}var Vl;no.RegisterExtension(Bl,(e=>new Gl(e))),function(e){e[e.Input=0]="Input",e[e.Output=1]="Output"}(Vl||(Vl={}));class kl{constructor(e,t,i){this._ownerBlock=i,this._connectedPoint=[],this.uniqueId=Gt(),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(Yt.Instantiate(e.className))(e.name,e._connectionType,t);return i.deserialize(e),i}}class Xl{constructor(e){this.value=this._toInt(e)}_toInt(e){return 0|e}add(e){return new Xl(this.value+e.value)}subtract(e){return new Xl(this.value-e.value)}multiply(e){return new Xl(Math.imul(this.value,e.value))}divide(e){return new Xl(this.value/e.value)}getClassName(){return Xl.ClassName}equals(e){return this.value===e.value}static Parse(e){return new Xl(e.value)}}Xl.ClassName="FlowGraphInteger",M("FlowGraphInteger",Xl);class Hl{constructor(e,t){this.typeName=e,this.defaultValue=t}serialize(e){e.typeName=this.typeName,e.defaultValue=this.defaultValue}static Parse(e){return new Hl(e.typeName,e.defaultValue)}}const Wl=new Hl("any",void 0),zl=new Hl("number",0),Yl=new Hl("boolean",!1),Kl=new Hl("Vector2",U.Zero()),ql=new Hl("Vector3",B.Zero());new Hl("Vector4",G.Zero());const jl=new Hl("Matrix",k.Identity());new Hl("Color3",ee.Black()),new Hl("Quaternion",V.Identity());const Ql=new Hl("FlowGraphInteger",new Xl(0));class Zl extends kl{constructor(e,t,i,n){super(e,t,i),this.richType=n}_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=kl.Parse(e,t);return i.richType=Hl.Parse(e.richType),i}}function Jl(e){return"Mesh"===e||"AbstractMesh"===e||"GroundMesh"===e||"InstanceMesh"===e||"LinesMesh"===e||"GoldbergMesh"===e||"GreasedLineMesh"===e||"TrailMesh"===e}function $l(e){return"Vector2"===e||"Vector3"===e||"Vector4"===e||"Quaternion"===e||"Color3"===e||"Color4"===e}function ec(e,t,i){const n=t?.getClassName?.()??"";Jl(n)?i[e]={name:t.name,className:n}:$l(n)?i[e]={value:t.asArray(),className:n}:i[e]=t}function tc(e,t,i){const n=t[e];let r;const s=n?.className;return r=Jl(s)?i.getMeshByName(n.name):$l(s)?function(e,t){if("Vector2"===e)return U.FromArray(t);if("Vector3"===e)return B.FromArray(t);if("Vector4"===e)return G.FromArray(t);if("Quaternion"===e)return V.FromArray(t);if("Color3"===e)return new ee(t[0],t[1],t[2]);if("Color4"===e)return new te(t[0],t[1],t[2],t[3]);throw new Error(`Unknown vector class name ${e}`)}(s,n.value):"Matrix"===s?k.FromArray(n.value):s===Xl.ClassName?Xl.Parse(n):n&&void 0!==n.value?n.value:n,r}M("FGDataConnection",Zl);class ic{constructor(e){this.config=e,this.uniqueId=Gt(),this.name=this.config?.name??this.getClassName(),this.dataInputs=[],this.dataOutputs=[]}_updateOutputs(e){}registerDataInput(e,t){const i=new Zl(e,0,this,t);return this.dataInputs.push(i),i}registerDataOutput(e,t){const i=new Zl(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=ec){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=Yt.Instantiate(e.className),n={},r=t.valueParseFunction??tc;if(e.config)for(const i in e.config)n[i]=r(i,e.config,t.scene);var s;("FGSetPropertyBlock"===(s=e.className)||"FGGetPropertyBlock"===s||"FGPlayAnimationBlock"===s||"FGMeshPickEventBlock"===s)&&(n.pathConverter=t.pathConverter);const a=new i(n);a.uniqueId=e.uniqueId;for(let t=0;t<e.dataInputs.length;t++){const i=a.getDataInput(e.dataInputs[t].name);if(!i)throw new Error("Could not find data input with name "+e.dataInputs[t].name+" in block "+e.className);i.deserialize(e.dataInputs[t])}for(let t=0;t<e.dataOutputs.length;t++){const i=a.getDataOutput(e.dataOutputs[t].name);if(!i)throw new Error("Could not find data output with name "+e.dataOutputs[t].name+" in block "+e.className);i.deserialize(e.dataOutputs[t])}return a.metadata=e.metadata,a.deserialize&&a.deserialize(e),a}}class nc extends kl{_isSingularConnection(){return 1===this.connectionType}_activateSignal(e){0===this.connectionType?(e._notifyExecuteNode(this._ownerBlock),this._ownerBlock._execute(e,this),e._increaseExecutionId()):this._connectedPoint[0]?._activateSignal(e)}}M("FlowGraphSignalConnection",nc);class rc extends ic{constructor(e){super(e),this.signalInputs=[],this.signalOutputs=[],this.in=this._registerSignalInput("in")}_registerSignalInput(e){const t=new nc(e,0,this);return this.signalInputs.push(t),t}_registerSignalOutput(e){const t=new nc(e,1,this);return this.signalOutputs.push(t),t}getSignalInput(e){return this.signalInputs.find((t=>t.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<e.signalInputs.length;t++){const i=this.getSignalInput(e.signalInputs[t].name);if(!i)throw new Error("Could not find signal input with name "+e.signalInputs[t].name+" in block "+e.className);i.deserialize(e.signalInputs[t])}for(let t=0;t<e.signalOutputs.length;t++){const i=this.getSignalOutput(e.signalOutputs[t].name);if(!i)throw new Error("Could not find signal output with name "+e.signalOutputs[t].name+" in block "+e.className);i.deserialize(e.signalOutputs[t])}}getClassName(){return"FGExecutionBlock"}}class sc extends rc{constructor(e){super(e),this.out=this._registerSignalOutput("out"),this.done=this._registerSignalOutput("done")}_startPendingTasks(e){this._preparePendingTasks(e),e._addPendingBlock(this)}}class ac extends sc{_execute(e){e._notifyExecuteNode(this),this.out._activateSignal(e)}}class oc{constructor(e){this.uniqueId=Gt(),this._userVariables={},this._executionVariables={},this._connectionValues={},this._pendingBlocks=[],this._executionId=0,this.onNodeExecutedObservable=new g,this._configuration=e}hasVariable(e){return e in this._userVariables}setVariable(e,t){this._userVariables[e]=t}getVariable(e){return this._userVariables[e]}get userVariables(){return this._userVariables}_getUniqueIdPrefixedName(e,t){return`${e.uniqueId}_${t}`}_setExecutionVariable(e,t,i){this._executionVariables[this._getUniqueIdPrefixedName(e,t)]=i}_getExecutionVariable(e,t,i){return this._hasExecutionVariable(e,t)?this._executionVariables[this._getUniqueIdPrefixedName(e,t)]:i}_deleteExecutionVariable(e,t){delete this._executionVariables[this._getUniqueIdPrefixedName(e,t)]}_hasExecutionVariable(e,t){return this._getUniqueIdPrefixedName(e,t)in this._executionVariables}_hasConnectionValue(e){return e.uniqueId in this._connectionValues}_setConnectionValue(e,t){this._connectionValues[e.uniqueId]=t}_getConnectionValue(e){return this._connectionValues[e.uniqueId]}get configuration(){return this._configuration}_addPendingBlock(e){this._pendingBlocks.push(e)}_removePendingBlock(e){const t=this._pendingBlocks.indexOf(e);-1!==t&&this._pendingBlocks.splice(t,1)}_clearPendingBlocks(){for(const e of this._pendingBlocks)e._cancelPendingTasks(this);this._pendingBlocks.length=0}_notifyExecuteNode(e){this.onNodeExecutedObservable.notifyObservers(e)}_increaseExecutionId(){this._executionId++}get executionId(){return this._executionId}serialize(e={},t=ec){e.uniqueId=this.uniqueId,e._userVariables={};for(const i in this._userVariables)t(i,this._userVariables[i],e._userVariables);e._connectionValues={};for(const i in this._connectionValues)t(i,this._connectionValues[i],e._connectionValues)}getClassName(){return"FGContext"}static Parse(e,t){const i=t.graph.createContext(),n=t.valueParseFunction??tc;i.uniqueId=e.uniqueId;for(const t in e._userVariables){const r=n(t,e._userVariables,i._configuration.scene);i._userVariables[t]=r}for(const t in e._connectionValues){const r=n(t,e._connectionValues,i._configuration.scene);i._connectionValues[t]=r}return i}}function lc(e,t){return!(!e.parent||e.parent!==t&&!lc(e.parent,t))}e([a()],oc.prototype,"uniqueId",void 0);class cc extends ac{constructor(e){super(e),this.config=e}_getReferencedMesh(){const e=this.config.pathConverter.convert(this.config.path),t=e.info.getObject(e.object);if(!(t&&t instanceof Vi))throw new Error("Mesh pick event block requires a valid mesh");return t}_preparePendingTasks(e){let t=e._getExecutionVariable(this,"meshPickObserver");if(!t){const i=this._getReferencedMesh();e._setExecutionVariable(this,"mesh",i),t=i.getScene().onPointerObservable.add((t=>{t.type===cn.POINTERPICK&&t.pickInfo?.pickedMesh&&(t.pickInfo?.pickedMesh===i||lc(t.pickInfo?.pickedMesh,i))&&this._execute(e)}));const n=i.onDisposeObservable.add((()=>this._onDispose));e._setExecutionVariable(this,"meshPickObserver",t),e._setExecutionVariable(this,"meshDisposeObserver",n)}}_onDispose(e){this._cancelPendingTasks(e),e._removePendingBlock(this)}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"mesh"),i=e._getExecutionVariable(this,"meshPickObserver"),n=e._getExecutionVariable(this,"meshDisposeObserver");t.getScene().onPointerObservable.remove(i),t.onDisposeObservable.remove(n),e._deleteExecutionVariable(this,"mesh"),e._deleteExecutionVariable(this,"meshPickObserver"),e._deleteExecutionVariable(this,"meshDisposeObserver")}getClassName(){return cc.ClassName}serialize(e){super.serialize(e),e.config.path=this.config.path}}var hc,dc;cc.ClassName="FGMeshPickEventBlock",M(cc.ClassName,cc),function(e){e[e.Stopped=0]="Stopped",e[e.Started=1]="Started"}(hc||(hc={}));class uc{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 oc({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()===cc.ClassName){const i=t._getReferencedMesh();let n=0;for(;n<e.length;n++){const t=e[n]._getReferencedMesh();if(i&&t&&lc(i,t))break}e.splice(n,0,t)}else e.push(t);return e}dispose(){if(0!==this.state){this.state=0;for(const e of this._executionContexts)e._clearPendingBlocks();this._executionContexts.length=0,this._eventBlocks.length=0,this._scene.onDisposeObservable.remove(this._sceneDisposeObserver),this._sceneDisposeObserver=null}}visitAllBlocks(e){const t=[],i=new Set;for(const e of this._eventBlocks)t.push(e),i.add(e.uniqueId);for(;t.length>0;){const n=t.pop();e(n);for(const e of n.dataInputs)for(const n of e._connectedPoint)i.has(n._ownerBlock.uniqueId)||(t.push(n._ownerBlock),i.add(n._ownerBlock.uniqueId));if(n instanceof rc)for(const e of n.signalOutputs)for(const n of e._connectedPoint)i.has(n._ownerBlock.uniqueId)||(t.push(n._ownerBlock),i.add(n._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 n={};i.serialize(n,t),e.executionContexts.push(n)}}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 rc)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(),n=[],r=t.valueParseFunction??tc;for(const s of e.allBlocks){const e=ic.Parse(s,{scene:t.coordinator.config.scene,pathConverter:t.pathConverter,valueParseFunction:r});n.push(e),e instanceof ac&&i.addEventBlock(e)}for(const e of n){for(const t of e.dataInputs)for(const e of t.connectedPointIds){const i=uc.GetDataOutConnectionByUniqueId(n,e);t.connectTo(i)}if(e instanceof rc)for(const t of e.signalOutputs)for(const e of t.connectedPointIds){const i=uc.GetSignalInConnectionByUniqueId(n,e);t.connectTo(i)}}for(const t of e.executionContexts)oc.Parse(t,{graph:i,valueParseFunction:r});return i}}class fc{constructor(e){this.config=e,this._flowGraphs=[],this._customEventsMap=new Map,this.config.scene.onDisposeObservable.add((()=>{this.dispose()}));(fc.SceneCoordinators.get(this.config.scene)??[]).push(this)}createGraph(){const e=new uc({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=fc.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 n={};i.serialize(n,t),e._flowGraphs.push(n)}))}static Parse(e,t){const i=t.valueParseFunction??tc,n=new fc({scene:t.scene});return e._flowGraphs?.forEach((e=>{uc.Parse(e,{coordinator:n,valueParseFunction:i,pathConverter:t.pathConverter})})),n}get flowGraphs(){return this._flowGraphs}getCustomEventObservable(e){let t=this._customEventsMap.get(e);return t||(t=new g,this._customEventsMap.set(e,t)),t}notifyCustomEvent(e,t){const i=this._customEventsMap.get(e);i&&i.notifyObservers(t)}}fc.SceneCoordinators=new Map;class _c extends ac{_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 _c.ClassName}}_c.ClassName="FGSceneReadyEventBlock",M("FGSceneReadyEventBlock",_c);class mc extends ac{_preparePendingTasks(e){if(!e._getExecutionVariable(this,"sceneBeforeRender")){const t=e.configuration.scene.onBeforeRenderObservable.add((()=>{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 mc.ClassName}}mc.ClassName="FGSceneTickEventBlock",M(mc.ClassName,mc);class pc extends rc{constructor(e){super(e),this.out=this._registerSignalOutput("out")}}class gc extends pc{constructor(e){super(e),this.message=this.registerDataInput("message",Wl)}_execute(e){const t=this.message.getValue(e);de.Log(t),this.out._activateSignal(e)}getClassName(){return gc.ClassName}}gc.ClassName="FGConsoleLogBlock",M(gc.ClassName,gc),function(e){e[e.INIT=0]="INIT",e[e.STARTED=1]="STARTED",e[e.ENDED=2]="ENDED"}(dc||(dc={}));class Ec{constructor(e){this.onEachCountObservable=new g,this.onTimerAbortedObservable=new g,this.onTimerEndedObservable=new g,this.onStateChangedObservable=new g,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},n=this._breakOnNextTick||this._breakCondition(i);n||this._timer>=this._timeToEnd?this._stop(i,n):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 Tc extends sc{constructor(e){super(e),this.timeout=this.registerDataInput("timeout",zl)}_preparePendingTasks(e){const t=this.timeout.getValue(e);if(void 0!==t&&t>=0){const i=e._getExecutionVariable(this,"runningTimers")||[],n=e.configuration.scene,r=new Ec({timeout:t,contextObservable:n.onBeforeRenderObservable,onEnded:()=>this._onEnded(r,e)});r.start(),i.push(r),e._setExecutionVariable(this,"runningTimers",i)}}_execute(e){this._startPendingTasks(e),this.out._activateSignal(e)}_onEnded(e,t){const i=t._getExecutionVariable(this,"runningTimers")||[],n=i.indexOf(e);-1!==n?i.splice(n,1):Yt.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 Tc.ClassName}}Tc.ClassName="FGTimerBlock",M("FGTimerBlock",Tc);class Ac extends pc{constructor(e){super(e),this.config=e;for(let e=0;e<this.config.eventData.length;e++){const t=this.config.eventData[e];this.registerDataInput(t,Wl)}}_execute(e){const t=this.config.eventId,i=this.dataInputs.map((t=>t.getValue(e)));e.configuration.coordinator.notifyCustomEvent(t,i),this.out._activateSignal(e)}getClassName(){return Ac.ClassName}}Ac.ClassName="FGSendCustomEventBlock",M("FGSendCustomEventBlock",Ac);class vc extends ac{constructor(e){super(e),this.config=e;for(let e=0;e<this.config.eventData.length;e++){const t=this.config.eventData[e];this.registerDataOutput(t,Wl)}}_preparePendingTasks(e){const t=e.configuration.coordinator.getCustomEventObservable(this.config.eventId);this._eventObserver=t.add((t=>{for(let i=0;i<t.length;i++)this.dataOutputs[i].setValue(t[i],e);this._execute(e)}))}_cancelPendingTasks(e){const t=e.configuration.coordinator.getCustomEventObservable(this.config.eventId);t?t.remove(this._eventObserver):Yt.Warn(`FlowGraphReceiveCustomEventBlock: Missing observable for event ${this.config.eventId}`)}getClassName(){return vc.ClassName}serialize(e){super.serialize(e),e.eventId=this.config.eventId,e.eventData=this.config.eventData}}vc.ClassName="FGReceiveCustomEventBlock",M(vc.ClassName,vc);class Rc extends rc{constructor(e){super(e),this.config=e,this.outFlows=[];for(let e=0;e<this.config.numberOutputFlows;e++)this.outFlows.push(this._registerSignalOutput(`${e}`))}_execute(e){for(let t=0;t<this.config.numberOutputFlows;t++)this.outFlows[t]._activateSignal(e)}getClassName(){return Rc.ClassName}}Rc.ClassName="FGSequenceBlock",M(Rc.ClassName,Rc);const Sc=new RegExp(/\{(\w+)\}/g);class Ic{constructor(e,t){this.path=e,this.ownerBlock=t,this.templatedInputs=[];let i=Sc.exec(e);for(;i;){const[,n]=i;this.templatedInputs.push(t.registerDataInput(n,Ql)),i=Sc.exec(e)}}getAccessor(e,t){let i=this.path;for(const e of this.templatedInputs){const n=e.getValue(t).value;i=i.replace(`{${e.name}}`,n.toString())}return e.convert(i)}}class Cc extends ic{constructor(e){super(e),this.config=e,this.value=this.registerDataOutput("value",Wl),this.templateComponent=new Ic(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 Cc.ClassName}serialize(e={}){super.serialize(e),e.config.path=this.config.path}}Cc.ClassName="FGGetPropertyBlock",M(Cc.ClassName,Cc);class Mc extends pc{constructor(e){super(e),this.config=e,this.a=this.registerDataInput("a",Wl),this.templateComponent=new Ic(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 Mc.ClassName}}Mc.ClassName="FGSetPropertyBlock",M("FGSetPropertyBlock",Mc);const xc="cachedOperationValue",bc="cachedExecutionId";class yc extends ic{constructor(e,t){super(t),this.value=this.registerDataOutput("value",e)}_updateOutputs(e){const t=e._getExecutionVariable(this,bc),i=e._getExecutionVariable(this,xc);if(void 0!==i&&t===e.executionId)this.value.setValue(i,e);else{const t=this._doOperation(e);e._setExecutionVariable(this,xc,t),e._setExecutionVariable(this,bc,e.executionId),this.value.setValue(t,e)}}}class Oc extends yc{constructor(e,t,i,n,r,s){super(i,s),this._operation=n,this._className=r,this.a=this.registerDataInput("a",e),this.b=this.registerDataInput("b",t)}_doOperation(e){return this._operation(this.a.getValue(e),this.b.getValue(e))}getClassName(){return this._className}}class Dc extends yc{constructor(e,t,i,n){super(e,n),this._operation=t,this._className=i}_doOperation(e){return this._operation()}getClassName(){return this._className}}class Nc extends yc{constructor(e,t,i,n,r){super(t,r),this._operation=i,this._className=n,this.a=this.registerDataInput("a",e)}_doOperation(e){return this._operation(this.a.getValue(e))}getClassName(){return this._className}}class Pc extends yc{constructor(e,t,i,n,r,s,a){super(n,a),this._operation=r,this._className=s,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 Lc(e){return e.getClassName?e.getClassName():""}function Fc(e,t){return"Vector2"===e&&"Vector2"===t||"Vector3"===e&&"Vector3"===t||"Vector4"===e&&"Vector4"===t}function wc(e,t){return"Matrix"===e&&"Matrix"===t}function Uc(e,t){return"FlowGraphInteger"===e&&"FlowGraphInteger"===t}class Bc extends Oc{constructor(e){super(Wl,Wl,Wl,((e,t)=>this._polymorphicAdd(e,t)),Bc.ClassName,e)}_polymorphicAdd(e,t){const i=Lc(e),n=Lc(t);return Fc(i,n)||wc(i,n)||Uc(i,n)?e.add(t):e+t}}Bc.ClassName="FGAddBlock",M(Bc.ClassName,Bc);class Gc extends Oc{constructor(e){super(Wl,Wl,Wl,((e,t)=>this._polymorphicAdd(e,t)),Gc.ClassName,e)}_polymorphicAdd(e,t){const i=Lc(e),n=Lc(t);return Fc(i,n)||Uc(i,n)?e.subtract(t):wc(i,n)?e.add(t.scale(-1)):e-t}}Gc.ClassName="FGSubBlock",M(Gc.ClassName,Gc);class Vc extends Oc{constructor(e){super(Wl,Wl,Wl,((e,t)=>this._polymorphicMultiply(e,t)),Vc.ClassName,e)}_polymorphicMultiply(e,t){const i=Lc(e),n=Lc(t);return Fc(i,n)||Uc(i,n)?e.multiply(t):wc(i,n)?k.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}}Vc.ClassName="FGMultiplyBlock",M(Vc.ClassName,Vc);class kc extends Oc{constructor(e){super(Wl,Wl,Wl,((e,t)=>this._polymorphicDivide(e,t)),kc.ClassName,e)}_polymorphicDivide(e,t){const i=Lc(e),n=Lc(t);return Fc(i,n)||Uc(i,n)?e.divide(t):wc(i,n)?k.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}}kc.ClassName="FGDivideBlock",M(kc.ClassName,kc);class Xc extends Dc{constructor(e){super(zl,(()=>Math.random()),Xc.ClassName,e)}}Xc.ClassName="FGRandomBlock",M(Xc.ClassName,Xc);class Hc extends Oc{constructor(e){super(Wl,Wl,zl,((e,t)=>this._polymorphicDot(e,t)),Hc.ClassName,e)}_polymorphicDot(e,t){switch(Lc(e)){case"Vector2":return U.Dot(e,t);case"Vector3":return B.Dot(e,t);case"Vector4":return G.Dot(e,t);default:throw new Error(`Cannot get dot product of ${e} and ${t}`)}}}Hc.ClassName="FGDotBlock",M(Hc.ClassName,Hc);class Wc extends Dc{constructor(e){super(zl,(()=>Math.E),Wc.ClassName,e)}}Wc.ClassName="FGEBlock",M(Wc.ClassName,Wc);class zc extends Dc{constructor(e){super(zl,(()=>Math.PI),zc.ClassName,e)}}zc.ClassName="FGPIBlock",M(zc.ClassName,zc);class Yc extends Dc{constructor(e){super(zl,(()=>Number.POSITIVE_INFINITY),Yc.ClassName,e)}}Yc.ClassName="FGInfBlock",M(Yc.ClassName,Yc);class Kc extends Dc{constructor(e){super(zl,(()=>Number.NaN),Kc.ClassName,e)}}function qc(e,t){switch(Lc(e)){case"FlowGraphInteger":return new Xl(t(e.value));case"Vector2":return new U(t(e.x),t(e.y));case"Vector3":return new B(t(e.x),t(e.y),t(e.z));case"Vector4":return new G(t(e.x),t(e.y),t(e.z),t(e.w));case"Matrix":return k.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)}}Kc.ClassName="FGNaNBlock",M(Kc.ClassName,Kc);class jc extends Nc{constructor(e){super(Wl,Wl,(e=>this._polymorphicAbs(e)),jc.ClassName,e)}_polymorphicAbs(e){return qc(e,Math.abs)}}jc.ClassName="FGAbsBlock",M(jc.ClassName,jc);class Qc extends Nc{constructor(e){super(Wl,Wl,(e=>this._polymorphicSign(e)),Qc.ClassName,e)}_polymorphicSign(e){return qc(e,Math.sign)}}Qc.ClassName="FGSignBlock",M(Qc.ClassName,Qc);class Zc extends Nc{constructor(e){super(Wl,Wl,(e=>this._polymorphicTrunc(e)),Zc.ClassName,e)}_polymorphicTrunc(e){return qc(e,Math.trunc)}}Zc.ClassName="FGTruncBlock",M(Zc.ClassName,Zc);class Jc extends Nc{constructor(e){super(Wl,Wl,(e=>this._polymorphicFloor(e)),Jc.ClassName,e)}_polymorphicFloor(e){return qc(e,Math.floor)}}Jc.ClassName="FGFloorBlock",M(Jc.ClassName,Jc);class $c extends Nc{constructor(e){super(Wl,Wl,(e=>this._polymorphicCeiling(e)),$c.ClassName,e)}_polymorphicCeiling(e){return qc(e,Math.ceil)}}$c.ClassName="FGCeilBlock",M($c.ClassName,$c);class eh extends Nc{constructor(e){super(Wl,Wl,(e=>this._polymorphicFract(e)),eh.ClassName,e)}_polymorphicFract(e){return qc(e,(e=>e-Math.floor(e)))}}eh.ClassName="FGFractBlock",M(eh.ClassName,eh);class th extends Nc{constructor(e){super(Wl,Wl,(e=>this._polymorphicNeg(e)),th.ClassName,e)}_polymorphicNeg(e){return qc(e,(e=>-e))}}function ih(e,t,i){switch(Lc(e)){case"FlowGraphInteger":return new Xl(i(e.value,t.value));case"Vector2":return new U(i(e.x,t.x),i(e.y,t.y));case"Vector3":return new B(i(e.x,t.x),i(e.y,t.y),i(e.z,t.z));case"Vector4":return new G(i(e.x,t.x),i(e.y,t.y),i(e.z,t.z),i(e.w,t.w));case"Matrix":return k.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)}}th.ClassName="FGNegBlock",M(th.ClassName,th);class nh extends Oc{constructor(e){super(Wl,Wl,Wl,((e,t)=>this._polymorphicRemainder(e,t)),nh.ClassName,e)}_polymorphicRemainder(e,t){return ih(e,t,((e,t)=>e%t))}}nh.ClassName="FGRemainderBlock",M(nh.ClassName,nh);class rh extends Oc{constructor(e){super(Wl,Wl,Wl,((e,t)=>this._polymorphicMin(e,t)),rh.ClassName,e)}_polymorphicMin(e,t){return ih(e,t,Math.min)}}rh.ClassName="FGMinBlock",M(rh.ClassName,rh);class sh extends Oc{constructor(e){super(Wl,Wl,Wl,((e,t)=>this._polymorphicMax(e,t)),sh.ClassName,e)}_polymorphicMax(e,t){return ih(e,t,Math.max)}}function ah(e,t,i){return Math.min(Math.max(e,Math.min(t,i)),Math.max(t,i))}function oh(e,t,i,n){switch(Lc(e)){case"FlowGraphInteger":return new Xl(n(e.value,t.value,i.value));case"Vector2":return new U(n(e.x,t.x,i.x),n(e.y,t.y,i.y));case"Vector3":return new B(n(e.x,t.x,i.x),n(e.y,t.y,i.y),n(e.z,t.z,i.z));case"Vector4":return new G(n(e.x,t.x,i.x),n(e.y,t.y,i.y),n(e.z,t.z,i.z),n(e.w,t.w,i.w));case"Matrix":return k.FromValues(n(e.m[0],t.m[0],i.m[0]),n(e.m[4],t.m[4],i.m[4]),n(e.m[8],t.m[8],i.m[8]),n(e.m[12],t.m[12],i.m[12]),n(e.m[1],t.m[1],i.m[1]),n(e.m[5],t.m[5],i.m[5]),n(e.m[9],t.m[9],i.m[9]),n(e.m[13],t.m[13],i.m[13]),n(e.m[2],t.m[2],i.m[2]),n(e.m[6],t.m[6],i.m[6]),n(e.m[10],t.m[10],i.m[10]),n(e.m[14],t.m[14],i.m[14]),n(e.m[3],t.m[3],i.m[3]),n(e.m[7],t.m[7],i.m[7]),n(e.m[11],t.m[11],i.m[11]),n(e.m[15],t.m[15],i.m[15]));default:return n(e,t,i)}}sh.ClassName="FGMaxBlock",M(sh.ClassName,sh);class lh extends Pc{constructor(e){super(Wl,Wl,Wl,Wl,((e,t,i)=>this._polymorphicClamp(e,t,i)),lh.ClassName,e)}_polymorphicClamp(e,t,i){return oh(e,t,i,ah)}}function ch(e){return Math.min(Math.max(e,0),1)}lh.ClassName="FGClampBlock",M(lh.ClassName,lh);class hh extends Nc{constructor(e){super(Wl,Wl,(e=>this._polymorphicSaturate(e)),hh.ClassName,e)}_polymorphicSaturate(e){return qc(e,ch)}}hh.ClassName="FGSaturateBlock",M(hh.ClassName,hh);class dh extends Pc{constructor(e){super(Wl,Wl,Wl,Wl,((e,t,i)=>this._polymorphicInterpolate(e,t,i)),dh.ClassName,e)}_interpolate(e,t,i){return(1-i)*e+i*t}_polymorphicInterpolate(e,t,i){return oh(e,t,i,this._interpolate)}}dh.ClassName="FGInterpolateBlock",M(dh.ClassName,dh);class uh extends Oc{constructor(e){super(Wl,Wl,Yl,((e,t)=>this._polymorphicEq(e,t)),uh.ClassName,e)}_polymorphicEq(e,t){const i=Lc(e),n=Lc(t);return Fc(i,n)||wc(i,n)||Uc(i,n)?e.equals(t):e===t}}function fh(e,t,i){const n=Lc(e);if(n===Lc(t)){if(""===n)return i(e,t);if("FlowGraphInteger"===n)return i(e.value,t.value);throw new Error(`Cannot compare ${e} and ${t}`)}throw new Error(`${e} and ${t} are of different types.`)}uh.ClassName="FGEqBlock",M(uh.ClassName,uh);class _h extends Oc{constructor(e){super(Wl,Wl,Yl,((e,t)=>this._polymorphicLessThan(e,t)),_h.ClassName,e)}_polymorphicLessThan(e,t){return fh(e,t,((e,t)=>e<t))}}_h.ClassName="FGLessThanBlock",M(_h.ClassName,_h);class mh extends Oc{constructor(e){super(Wl,Wl,Yl,((e,t)=>this._polymorphicLessThanOrEqual(e,t)),mh.ClassName,e)}_polymorphicLessThanOrEqual(e,t){return fh(e,t,((e,t)=>e<=t))}}mh.ClassName="FGLessThanOrEqualBlock";class ph extends Oc{constructor(e){super(Wl,Wl,Yl,((e,t)=>this._polymorphicGreaterThan(e,t)),ph.ClassName,e)}_polymorphicGreaterThan(e,t){return fh(e,t,((e,t)=>e>t))}}ph.ClassName="FGGreaterThanBlock",M(ph.ClassName,ph);class gh extends Oc{constructor(e){super(Wl,Wl,Yl,((e,t)=>this._polymorphicGreaterThanOrEqual(e,t)),gh.ClassName,e)}_polymorphicGreaterThanOrEqual(e,t){return fh(e,t,((e,t)=>e>=t))}}gh.ClassName="FGGreaterThanOrEqualBlock",M(gh.ClassName,gh);class Eh extends Nc{constructor(e){super(Wl,Yl,(e=>this._polymorphicIsNan(e)),Eh.ClassName,e)}_polymorphicIsNan(e){const t=Lc(e);if(""===t)return isNaN(e);if("FlowGraphInteger"===t)return isNaN(e.value);throw new Error(`Cannot get NaN of ${e}`)}}Eh.ClassName="FGIsNanBlock",M(Eh.ClassName,Eh);class Th extends Nc{constructor(e){super(Wl,Yl,(e=>this._polymorphicIsInf(e)),Th.ClassName,e)}_polymorphicIsInf(e){const t=Lc(e);if(""===t)return!isFinite(e);if("FlowGraphInteger"===t)return!isFinite(e.value);throw new Error(`Cannot get isInf of ${e}`)}}Th.ClassName="FGIsInfBlock";class Ah extends Nc{constructor(e){super(Wl,Wl,(e=>this._polymorphicDegToRad(e)),Ah.ClassName,e)}_degToRad(e){return e*Math.PI/180}_polymorphicDegToRad(e){return qc(e,this._degToRad)}}Ah.ClassName="FGDegToRadBlock",M(Ah.ClassName,Ah);class vh extends Nc{constructor(e){super(Wl,Wl,(e=>this._polymorphicRadToDeg(e)),vh.ClassName,e)}_radToDeg(e){return 180*e/Math.PI}_polymorphicRadToDeg(e){return qc(e,this._radToDeg)}}vh.ClassName="FGRadToDegBlock",M(vh.ClassName,vh);class Rh extends Nc{constructor(e){super(Wl,Wl,(e=>this._polymorphicSin(e)),Rh.ClassName,e)}_polymorphicSin(e){return qc(e,Math.sin)}}Rh.ClassName="FGSinBlock",M(Rh.ClassName,Rh);class Sh extends Nc{constructor(e){super(Wl,Wl,(e=>this._polymorphicCos(e)),Sh.ClassName,e)}_polymorphicCos(e){return qc(e,Math.cos)}}Sh.ClassName="FGCosBlock",M(Sh.ClassName,Sh);class Ih extends Nc{constructor(e){super(Wl,Wl,(e=>this._polymorphicTan(e)),Ih.ClassName,e)}_polymorphicTan(e){return qc(e,Math.tan)}}Ih.ClassName="FGTanBlock",M(Ih.ClassName,Ih);class Ch extends Nc{constructor(e){super(Wl,Wl,(e=>this._polymorphicAsin(e)),Ch.ClassName,e)}_polymorphicAsin(e){return qc(e,Math.asin)}}Ch.ClassName="FGAsinBlock",M(Ch.ClassName,Ch);class Mh extends Nc{constructor(e){super(Wl,Wl,(e=>this._polymorphicAcos(e)),Mh.ClassName,e)}_polymorphicAcos(e){return qc(e,Math.acos)}}Mh.ClassName="FGAcosBlock",M(Mh.ClassName,Mh);class xh extends Nc{constructor(e){super(Wl,Wl,(e=>this._polymorphicAtan(e)),xh.ClassName,e)}_polymorphicAtan(e){return qc(e,Math.atan)}}xh.ClassName="FGAtanBlock",M(xh.ClassName,xh);class bh extends Oc{constructor(e){super(Wl,Wl,Wl,((e,t)=>this._polymorphicAtan2(e,t)),bh.ClassName,e)}_polymorphicAtan2(e,t){return ih(e,t,Math.atan2)}}bh.ClassName="FGAtan2Block",M(bh.ClassName,bh);class yh extends Nc{constructor(e){super(Wl,Wl,(e=>this._polymorphicSinh(e)),yh.ClassName,e)}_polymorphicSinh(e){return qc(e,Math.sinh)}}yh.ClassName="FGSinhBlock",M(yh.ClassName,yh);class Oh extends Nc{constructor(e){super(Wl,Wl,(e=>this._polymorphicCosh(e)),Oh.ClassName,e)}_polymorphicCosh(e){return qc(e,Math.cosh)}}Oh.ClassName="FGCoshBlock",M(Oh.ClassName,Oh);class Dh extends Nc{constructor(e){super(Wl,Wl,(e=>this._polymorphicTanh(e)),Dh.ClassName,e)}_polymorphicTanh(e){return qc(e,Math.tanh)}}Dh.ClassName="FGTanhBlock",M(Dh.ClassName,Dh);class Nh extends Nc{constructor(e){super(Wl,zl,(e=>this._polymorphicAsinh(e)),Nh.ClassName,e)}_polymorphicAsinh(e){return qc(e,Math.asinh)}}Nh.ClassName="FGAsinhBlock",M(Nh.ClassName,Nh);class Ph extends Nc{constructor(e){super(Wl,zl,(e=>this._polymorphicAcosh(e)),Ph.ClassName,e)}_polymorphicAcosh(e){return qc(e,Math.acosh)}}Ph.ClassName="FGAcoshBlock",M(Ph.ClassName,Ph);class Lh extends Nc{constructor(e){super(Wl,zl,(e=>this._polymorphicAtanh(e)),Lh.ClassName,e)}_polymorphicAtanh(e){return qc(e,Math.atanh)}}Lh.ClassName="FGAtanhBlock",M(Lh.ClassName,Lh);class Fh extends Nc{constructor(e){super(Wl,zl,(e=>this._polymorphicExp(e)),Fh.ClassName,e)}_polymorphicExp(e){return qc(e,Math.exp)}}Fh.ClassName="FGExpBlock",M(Fh.ClassName,Fh);class wh extends Nc{constructor(e){super(Wl,zl,(e=>this._polymorphicLog(e)),wh.ClassName,e)}_polymorphicLog(e){return qc(e,Math.log)}}wh.ClassName="FGLogBlock",M(wh.ClassName,wh);class Uh extends Nc{constructor(e){super(Wl,zl,(e=>this._polymorphicLog2(e)),Uh.ClassName,e)}_polymorphicLog2(e){return qc(e,Math.log2)}}Uh.ClassName="FGLog2Block",M(Uh.ClassName,Uh);class Bh extends Nc{constructor(e){super(Wl,zl,(e=>this._polymorphicLog10(e)),Bh.ClassName,e)}_polymorphicLog10(e){return qc(e,Math.log10)}}Bh.ClassName="FGLog10Block",M(Bh.ClassName,Bh);class Gh extends Nc{constructor(e){super(Wl,zl,(e=>this._polymorphicSqrt(e)),Gh.ClassName,e)}_polymorphicSqrt(e){return qc(e,Math.sqrt)}}Gh.ClassName="FGSqrtBlock",M(Gh.ClassName,Gh);class Vh extends Nc{constructor(e){super(Wl,zl,(e=>this._polymorphicCubeRoot(e)),Vh.ClassName,e)}_polymorphicCubeRoot(e){return qc(e,Math.cbrt)}}Vh.ClassName="FGCubeRootBlock",M(Vh.ClassName,Vh);class kh extends Oc{constructor(e){super(Wl,zl,zl,((e,t)=>this._polymorphicPow(e,t)),kh.ClassName,e)}_polymorphicPow(e,t){return ih(e,t,Math.pow)}}kh.ClassName="FGPowBlock",M(kh.ClassName,kh);class Xh extends Nc{constructor(e){super(Wl,zl,(e=>this._polymorphicLength(e)),Xh.ClassName,e)}_polymorphicLength(e){switch(Lc(e)){case"Vector2":case"Vector3":case"Vector4":return e.length();default:throw new Error(`Cannot compute length of value ${e}`)}}}Xh.ClassName="FGLengthBlock",M(Xh.ClassName,Xh);class Hh extends Nc{constructor(e){super(Wl,Wl,(e=>this._polymorphicNormalize(e)),Hh.ClassName,e)}_polymorphicNormalize(e){switch(Lc(e)){case"Vector2":case"Vector3":case"Vector4":return e.normalize();default:throw new Error(`Cannot normalize value ${e}`)}}}Hh.ClassName="FGNormalizeBlock",M(Hh.ClassName,Hh);class Wh extends Oc{constructor(e){super(ql,ql,ql,((e,t)=>B.Cross(e,t)),Wh.ClassName,e)}}Wh.ClassName="FGCrossBlock",M(Wh.ClassName,Wh);class zh extends Oc{constructor(e){super(Kl,zl,Kl,((e,t)=>U.Transform(e,k.RotationZ(t))),zh.ClassName,e)}}zh.ClassName="FGRotate2DBlock",M(zh.ClassName,zh);class Yh extends Pc{constructor(e){super(ql,ql,zl,ql,((e,t,i)=>B.TransformCoordinates(e,k.RotationAxis(t,i))),Yh.ClassName,e)}}Yh.ClassName="FGRotate3DBlock",M(Yh.ClassName,Yh);class Kh extends Nc{constructor(e){super(jl,jl,(e=>k.Transpose(e)),Kh.ClassName,e)}}Kh.ClassName="FGTransposeBlock",M(Kh.ClassName,Kh);class qh extends Nc{constructor(e){super(jl,zl,(e=>e.determinant()),qh.ClassName,e)}}qh.ClassName="FGDeterminantBlock",M(qh.ClassName,qh);class jh extends Nc{constructor(e){super(jl,jl,(e=>k.Invert(e)),jh.ClassName,e)}}jh.ClassName="FGInvertMatrixBlock",M(jh.ClassName,jh);class Qh extends Oc{constructor(e){super(jl,jl,jl,((e,t)=>t.multiply(e)),Qh.ClassName,e)}}Qh.ClassName="FGMatMulBlock",M(Qh.ClassName,Qh);class Zh extends Nc{constructor(e){super(Ql,Ql,(e=>new Xl(~e.value)),Zh.ClassName,e)}}Zh.ClassName="FGBitwiseNotBlock",M(Zh.ClassName,Zh);class Jh extends Oc{constructor(e){super(Ql,Ql,Ql,((e,t)=>new Xl(e.value&t.value)),Jh.ClassName,e)}}Jh.ClassName="FGBitwiseAndBlock",M(Jh.ClassName,Jh);class $h extends Oc{constructor(e){super(Ql,Ql,Ql,((e,t)=>new Xl(e.value|t.value)),$h.ClassName,e)}}$h.ClassName="FGBitwiseOrBlock",M($h.ClassName,$h);class ed extends Oc{constructor(e){super(Ql,Ql,Ql,((e,t)=>new Xl(e.value^t.value)),ed.ClassName,e)}}ed.ClassName="FGBitwiseXorBlock",M(ed.ClassName,ed);class td extends Oc{constructor(e){super(Ql,Ql,Ql,((e,t)=>new Xl(e.value<<t.value)),td.ClassName,e)}}td.ClassName="FGBitwiseLeftShiftBlock",M(td.ClassName,td);class id extends Oc{constructor(e){super(Ql,Ql,Ql,((e,t)=>new Xl(e.value>>t.value)),id.ClassName,e)}}id.ClassName="FGBitwiseRightShiftBlock",M(id.ClassName,id);class nd extends Nc{constructor(e){super(Ql,Ql,(e=>new Xl(Math.clz32(e.value))),nd.ClassName,e)}}nd.ClassName="FGCountLeadingZerosBlock",M(nd.ClassName,nd);class rd extends Nc{constructor(e){super(Ql,Ql,(e=>new Xl(e.value?31-Math.clz32(e.value&-e.value):32)),rd.ClassName,e)}}rd.ClassName="FGCountTrailingZerosBlock",M(rd.ClassName,rd);class sd extends Nc{constructor(e){super(Ql,Ql,(e=>new Xl(function(e){let t=0;for(;e;)t+=1&e,e>>=1;return t}(e.value))),sd.ClassName,e)}}sd.ClassName="FGCountOneBitsBlock",M(sd.ClassName,sd);class ad extends pc{constructor(e={startIndex:new Xl(0)}){super(e),this.config=e,this.reset=this._registerSignalInput("reset"),this.n=this.registerDataInput("n",Ql),this.value=this.registerDataOutput("value",Ql)}_execute(e,t){if(t===this.reset)this.value.setValue(this.config.startIndex,e);else{const t=this.value.getValue(e);t.value<this.n.getValue(e).value&&(this.value.setValue(new Xl(t.value+1),e),this.out._activateSignal(e))}}getClassName(){return ad.ClassName}}ad.ClassName="FGDoNBlock",M(ad.ClassName,ad);class od extends ic{constructor(e){super(e),this.config=e,this.output=this.registerDataOutput(e.variableName,Wl)}_updateOutputs(e){const t=this.config.variableName;e.hasVariable(t)&&this.output.setValue(e.getVariable(t),e)}getClassName(){return od.ClassName}serialize(e){super.serialize(e),e.config.variableName=this.config.variableName}}od.ClassName="FGGetVariableBlock",M(od.ClassName,od);class ld extends pc{constructor(e){super(e),this.config=e,this.input=this.registerDataInput(e.variableName,Wl)}_execute(e){const t=this.config.variableName,i=this.input.getValue(e);e.setVariable(t,i),this.out._activateSignal(e)}getClassName(){return ld.ClassName}}ld.ClassName="FGSetVariableBlock",M(ld.ClassName,ld);class cd extends pc{constructor(e){super(e),this.config=e,this.condition=this.registerDataInput("condition",Yl),this.loopBody=this._registerSignalOutput("loopBody")}_execute(e,t){let i=this.condition.getValue(e);for(this.config?.isDo&&!i&&this.loopBody._activateSignal(e);i;)this.loopBody._activateSignal(e),i=this.condition.getValue(e);this.out._activateSignal(e)}getClassName(){return cd.ClassName}serialize(e){super.serialize(e),e.isDo=this.config?.isDo}}cd.ClassName="FGWhileLoopBlock",M(cd.ClassName,cd);const hd={"lifecycle/onStart":_c.ClassName,"lifecycle/onTick":mc.ClassName,log:gc.ClassName,"flow/delay":Tc.ClassName,"customEvent/send":Ac.ClassName,"customEvent/receive":vc.ClassName,"flow/sequence":Rc.ClassName,"world/get":Cc.ClassName,"world/set":Mc.ClassName,"flow/doN":ad.ClassName,"variable/get":od.ClassName,"variable/set":ld.ClassName,"flow/whileLoop":cd.ClassName,"math/random":Xc.ClassName,"math/e":Wc.ClassName,"math/pi":zc.ClassName,"math/inf":Yc.ClassName,"math/nan":Kc.ClassName,"math/abs":jc.ClassName,"math/sign":Qc.ClassName,"math/trunc":Zc.ClassName,"math/floor":Jc.ClassName,"math/ceil":$c.ClassName,"math/fract":eh.ClassName,"math/neg":th.ClassName,"math/add":Bc.ClassName,"math/sub":Gc.ClassName,"math/mul":Vc.ClassName,"math/div":kc.ClassName,"math/rem":nh.ClassName,"math/min":rh.ClassName,"math/max":sh.ClassName,"math/clamp":lh.ClassName,"math/saturate":hh.ClassName,"math/mix":dh.ClassName,"math/eq":uh.ClassName,"math/lt":_h.ClassName,"math/le":mh.ClassName,"math/gt":ph.ClassName,"math/ge":gh.ClassName,"math/isnan":Eh.ClassName,"math/isinf":Th.ClassName,"math/rad":Ah.ClassName,"math/deg":vh.ClassName,"math/sin":Rh.ClassName,"math/cos":Sh.ClassName,"math/tan":Ih.ClassName,"math/asin":Ch.ClassName,"math/acos":Mh.ClassName,"math/atan":xh.ClassName,"math/atan2":bh.ClassName,"math/sinh":yh.ClassName,"math/cosh":Oh.ClassName,"math/tanh":Dh.ClassName,"math/asinh":Nh.ClassName,"math/acosh":Ph.ClassName,"math/atanh":Lh.ClassName,"math/exp":Fh.ClassName,"math/log":wh.ClassName,"math/log2":Uh.ClassName,"math/log10":Bh.ClassName,"math/sqrt":Gh.ClassName,"math/cbrt":Vh.ClassName,"math/pow":kh.ClassName,"math/length":Xh.ClassName,"math/normalize":Hh.ClassName,"math/dot":Hc.ClassName,"math/cross":Wh.ClassName,"math/rotate2d":zh.ClassName,"math/rotate3d":Yh.ClassName,"math/transpose":Kh.ClassName,"math/determinant":qh.ClassName,"math/inverse":jh.ClassName,"math/matmul":Qh.ClassName,"math/not":Zh.ClassName,"math/and":Jh.ClassName,"math/or":$h.ClassName,"math/xor":ed.ClassName,"math/asr":id.ClassName,"math/lsl":td.ClassName,"math/clz":nd.ClassName,"math/ctz":rd.ClassName,"math/popcnt":sd.ClassName},dd={float2:"Vector2",float3:"Vector3",float4:"Vector4",float4x4:"Matrix",int:"FlowGraphInteger"};function ud(e,t,i){if(void 0!==e.type){const n=t.types&&t.types[e.type];if(!n)throw new Error(`${i}: Unknown type: ${e.type}`);const r=n.signature;if(!r)throw new Error(`${i}: Type ${e.type} has no signature`);const s=dd[r];return{value:e.value,className:s}}return e.value}function fd(e,t,i){const n=hd[t.type];if(!n)throw new Error(`/extensions/KHR_interactivity/nodes/${e}: Unknown block type: ${t.type}`);const r=e.toString(),s=function(e,t,i){const n={},r=e.configuration??[];for(const e of r)if("customEvent"===e.id){const r=t.customEvents&&t.customEvents[e.value];if(!r)throw new Error(`/extensions/KHR_interactivity/nodes/${i}: Unknown custom event: ${e.value}`);n.eventId=r.id,n.eventData=r.values.map((e=>e.id))}else if("variable"===e.id){const r=t.variables&&t.variables[e.value];if(!r)throw new Error(`/extensions/KHR_interactivity/nodes/${i}: Unknown variable: ${e.value}`);n.variableName=r.id}else if("path"===e.id){const t=e.value;n.path=t}else n[e.id]=ud(e,t,`/extensions/KHR_interactivity/nodes/${i}`);return n}(t,i,r);return{className:n,config:s,uniqueId:r,metadata:t.metadata,dataInputs:[],dataOutputs:[],signalInputs:[],signalOutputs:[]}}class _d extends Cl{constructor(e){super(e,md)}}const md={nodes:{__array__:{__target__:!0,translation:{type:"Vector3",get:e=>e._babylonTransformNode.position,set:(e,t)=>{t._babylonTransformNode.position=e},getObject:e=>e._babylonTransformNode}}}},pd="KHR_interactivity";class gd{constructor(e){this._loader=e,this.name=pd,this.enabled=this._loader.isExtensionUsed(pd),this._pathConverter=new _d(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:Gt(),_userVariables:{},_connectionValues:{}},i=[t],n=[];for(let t=0;t<e.nodes.length;t++){const i=fd(t,e.nodes[t],e);n.push(i)}for(let i=0;i<e.nodes.length;i++){const r=e.nodes[i],s=n[i],a=r.flows??[];for(const e of a){const t=e.id,r={uniqueId:Gt(),name:t,_connectionType:1,connectedPointIds:[]};s.signalOutputs.push(r);const a=e.node,o=e.socket,l=n[a];if(!l)throw new Error(`/extensions/KHR_interactivity/nodes/${i}: Could not find node with id ${a} that connects its input with with node ${i}'s output ${t}`);let c=l.signalInputs.find((e=>e.name===o));c||(c={uniqueId:Gt(),name:o,_connectionType:0,connectedPointIds:[]},l.signalInputs.push(c)),c.connectedPointIds.push(r.uniqueId),r.connectedPointIds.push(c.uniqueId)}const o=r.values??[];for(const r of o){const a=r.id,o={uniqueId:Gt(),name:a,_connectionType:0,connectedPointIds:[]};if(s.dataInputs.push(o),void 0!==r.value){const n=ud(r,e,`/extensions/KHR_interactivity/nodes/${i}`);t._connectionValues[o.uniqueId]=n}else{if(void 0===r.node||void 0===r.socket)throw new Error(`/extensions/KHR_interactivity/nodes/${i}: Invalid socket ${a} in node ${i}`);{const e=r.node,t=r.socket,s=n[e];if(!s)throw new Error(`/extensions/KHR_interactivity/nodes/${i}: Could not find node with id ${e} that connects its output with node${i}'s input ${a}`);let l=s.dataOutputs.find((e=>e.name===t));l||(l={uniqueId:Gt(),name:t,_connectionType:1,connectedPointIds:[]},s.dataOutputs.push(l)),o.connectedPointIds.push(l.uniqueId),l.connectedPointIds.push(o.uniqueId)}}}}const r=e.variables??[];for(let i=0;i<r.length;i++){const n=r[i],s=n.id;t._userVariables[s]=ud(n,e,`/extensions/KHR_interactivity/variables/${i}`)}return{allBlocks:n,executionContexts:i}}(t),n=new fc({scene:e});uc.Parse(i,{coordinator:n,pathConverter:this._pathConverter}),n.start()}}no.RegisterExtension(pd,(e=>new gd(e)));const Ed="ExtrasAsMetadata";class Td{_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=Ed,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 n=this._loader.createMaterial(e,t,i);return this._assignExtras(n,t),n}}function Ad(e,t){e?.scaling.setAll((t.maxZ-t.minZ)/2)}no.RegisterExtension(Ed,(e=>new Td(e)));const vd={backgroundColor:new te(.1,.1,.2,1)};class Rd{constructor(e,t){this._engine=e,this._skybox=null,this._isDisposed=!1,this._loadModelLock=new aa,this._loadModelAbortController=null,this._loadEnvironmentLock=new aa,this._environment=null,this._loadEnvironmentAbortController=null;const i={...vd,...t};this._details={scene:new Rr(this._engine),model:null},this._details.scene.clearColor=i.backgroundColor,this._camera=new kn("camera1",0,0,1,B.Zero(),this._details.scene),this._camera.attachControl(),this._updateCamera(),this.loadEnvironmentAsync(void 0).catch((()=>{})),this._engine.runRenderLoop((()=>{this._details.scene.render()})),t?.onInitialized?.(this._details)}async loadModelAsync(e,t,i){this._throwIfDisposedOrAborted(i),this._loadModelAbortController?.abort("New model is being loaded before previous model finished loading.");const n=this._loadModelAbortController=new AbortController;t={...t,pluginOptions:{...t?.pluginOptions,gltf:{...t?.pluginOptions?.gltf,extensionOptions:{...t?.pluginOptions?.gltf?.extensionOptions,KHR_audio:{enabled:!1},MSFT_audio_emitter:{enabled:!1}}}}},await this._loadModelLock.lockAsync((async()=>{this._throwIfDisposedOrAborted(i,n.signal),this._details.model?.dispose(),this._details.model=await yr(e,this._details.scene,t),this._details.model.addAllToScene(),this._updateCamera()}))}async loadEnvironmentAsync(e,t){this._throwIfDisposedOrAborted(t),this._loadEnvironmentAbortController?.abort("New environment is being loaded before previous environment finished loading.");const i=this._loadEnvironmentAbortController=new AbortController;await this._loadEnvironmentLock.lockAsync((async()=>{this._throwIfDisposedOrAborted(t,i.signal),this._environment?.dispose(),this._environment=await new Promise(((t,i)=>{if(e){const n=Js.CreateFromPrefilteredData(e,this._details.scene);this._details.scene.environmentTexture=n;const r=function(e,t,i,n){const r=ra("hdrSkyBox",void 0,e),s=new Hs("skyBox",e);return s.backFaceCulling=!1,s.reflectionTexture=i.clone(),s.reflectionTexture&&(s.reflectionTexture.coordinatesMode=Pr.SKYBOX_MODE),s.microSurface=1-n,s.disableLighting=!0,s.twoSidedLighting=!0,r.material=s,r.isPickable=!1,r.infiniteDistance=!0,r.ignoreCameraMaxZ=!0,Ad(r,t),r}(this._details.scene,this._camera,n,.3);this._skybox=r,this._details.scene.autoClear=!1;const s=()=>{n.dispose(),r.dispose(),this._skybox=null},a=n.onLoadObservable.addOnce((()=>{a.remove(),o.remove(),t({dispose:s})})),o=Pr.OnTextureLoadErrorObservable.add((e=>{e===n&&(a.remove(),o.remove(),s(),i(new Error("Failed to load environment texture.")))}))}else{const e=new Hn("hemilight",B.Up(),this._details.scene);this._details.scene.autoClear=!0,t(e)}}))}))}dispose(){this._details.scene.dispose(),this._isDisposed=!0}_updateCamera(){this._camera.useFramingBehavior=!0;const e=this._camera.getBehaviorByName("Framing");e.framingTime=0,e.elevationReturnTime=-1;let t=1;if(this._details.scene.meshes.length){this._camera.lowerRadiusLimit=null;const i=this._details.scene.getWorldExtends((e=>e.isVisible&&e.isEnabled()));e.zoomOnBoundingInfo(i.min,i.max);const n=i.max.subtract(i.min),r=i.min.add(n.scale(.5));t=1.2*n.length(),isFinite(t)||(t=1,r.copyFromFloats(0,0,0)),this._camera.setTarget(r)}this._camera.lowerRadiusLimit=.01*t,this._camera.wheelPrecision=100/t,this._camera.alpha=Math.PI/2,this._camera.beta=Math.PI/2,this._camera.radius=t,this._camera.minZ=.01*t,this._camera.maxZ=1e3*t,this._camera.speed=.2*t,this._camera.useAutoRotationBehavior=!0,this._camera.pinchPrecision=200/this._camera.radius,this._camera.upperRadiusLimit=5*this._camera.radius,this._camera.wheelDeltaPercentage=.01,this._camera.pinchDeltaPercentage=.01,this._camera.restoreStateInterpolationFactor=.1,Ad(this._skybox,this._camera)}_throwIfDisposedOrAborted(...e){if(this._isDisposed)throw new Error("Viewer is disposed.");for(const t of e)t?.throwIfAborted()}}class Sd{constructor(e=30){this._enabled=!0,this._rollingFrameTime=new Id(e)}sampleFrame(e=_e.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 Id{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}}function Cd(e){if(e.requestPointerLock){const t=e.requestPointerLock();t instanceof Promise?t.then((()=>{e.focus()})).catch((()=>{})):e.focus()}}Ni.prototype.setAlphaMode=function(e,t=!1){if(this._alphaMode!==e){switch(e){case Ze.ALPHA_DISABLE:this._alphaState.alphaBlend=!1;break;case Ze.ALPHA_PREMULTIPLIED:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case Ze.ALPHA_PREMULTIPLIED_PORTERDUFF: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 Ze.ALPHA_COMBINE: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 Ze.ALPHA_ONEONE:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ZERO,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case Ze.ALPHA_ADD:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE,this._gl.ZERO,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case Ze.ALPHA_SUBTRACT:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case Ze.ALPHA_MULTIPLY:this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR,this._gl.ZERO,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case Ze.ALPHA_MAXIMIZED: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 Ze.ALPHA_INTERPOLATE: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 Ze.ALPHA_SCREENMODE: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 Ze.ALPHA_ONEONE_ONEONE:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case Ze.ALPHA_ALPHATOCOLOR:this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_ALPHA,this._gl.ONE,this._gl.ZERO,this._gl.ZERO),this._alphaState.alphaBlend=!0;break;case Ze.ALPHA_REVERSEONEMINUS: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 Ze.ALPHA_SRC_DSTONEMINUSSRCALPHA: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 Ze.ALPHA_ONEONE_ONEZERO:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ONE,this._gl.ZERO),this._alphaState.alphaBlend=!0;break;case Ze.ALPHA_EXCLUSION: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 Ze.ALPHA_LAYER_ACCUMULATE: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=e===Ze.ALPHA_DISABLE),this._alphaMode=e}else if(!t){const t=e===Ze.ALPHA_DISABLE;this.depthCullingState.depthMask!==t&&(this.depthCullingState.depthMask=t)}},Ni.prototype.updateDynamicIndexBuffer=function(e,t,i=0){let n;this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER]=null,this.bindIndexBuffer(e),n=e.is32Bits?t instanceof Uint32Array?t:new Uint32Array(t):t instanceof Uint16Array?t:new Uint16Array(t),this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER,n,this._gl.DYNAMIC_DRAW),this._resetIndexBufferBinding()},Ni.prototype.updateDynamicVertexBuffer=function(e,t,i,n){this.bindArrayBuffer(e),void 0===i&&(i=0);const r=t.byteLength||t.length;void 0===n||n>=r&&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+n)):(t=t instanceof ArrayBuffer?new Uint8Array(t,i,n):new Uint8Array(t.buffer,t.byteOffset+i,n),this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,t)),this._resetVertexBufferBinding()},vt.prototype.displayLoadingUI=function(){if(!oe())return;const e=this.loadingScreen;e&&e.displayLoadingUI()},vt.prototype.hideLoadingUI=function(){if(!oe())return;const e=this._loadingScreen;e&&e.hideLoadingUI()},Object.defineProperty(vt.prototype,"loadingScreen",{get:function(){return!this._loadingScreen&&this._renderingCanvas&&(this._loadingScreen=vt.DefaultLoadingScreenFactory(this._renderingCanvas)),this._loadingScreen},set:function(e){this._loadingScreen=e},enumerable:!0,configurable:!0}),Object.defineProperty(vt.prototype,"loadingUIText",{set:function(e){this.loadingScreen.loadingUIText=e},enumerable:!0,configurable:!0}),Object.defineProperty(vt.prototype,"loadingUIBackgroundColor",{set:function(e){this.loadingScreen.loadingUIBackgroundColor=e},enumerable:!0,configurable:!0}),vt.prototype.getInputElement=function(){return this._renderingCanvas},vt.prototype.getRenderingCanvasClientRect=function(){return this._renderingCanvas?this._renderingCanvas.getBoundingClientRect():null},vt.prototype.getInputElementClientRect=function(){return this._renderingCanvas?this.getInputElement().getBoundingClientRect():null},vt.prototype.getAspectRatio=function(e,t=!1){const i=e.viewport;return this.getRenderWidth(t)*i.width/(this.getRenderHeight(t)*i.height)},vt.prototype.getScreenAspectRatio=function(){return this.getRenderWidth(!0)/this.getRenderHeight(!0)},vt.prototype._verifyPointerLock=function(){this._onPointerLockChange?.()},vt.prototype.setAlphaEquation=function(e){if(this._alphaEquation!==e){switch(e){case Ze.ALPHA_EQUATION_ADD:this._alphaState.setAlphaEquationParameters(Ze.GL_ALPHA_EQUATION_ADD,Ze.GL_ALPHA_EQUATION_ADD);break;case Ze.ALPHA_EQUATION_SUBSTRACT:this._alphaState.setAlphaEquationParameters(Ze.GL_ALPHA_EQUATION_SUBTRACT,Ze.GL_ALPHA_EQUATION_SUBTRACT);break;case Ze.ALPHA_EQUATION_REVERSE_SUBTRACT:this._alphaState.setAlphaEquationParameters(Ze.GL_ALPHA_EQUATION_REVERSE_SUBTRACT,Ze.GL_ALPHA_EQUATION_REVERSE_SUBTRACT);break;case Ze.ALPHA_EQUATION_MAX:this._alphaState.setAlphaEquationParameters(Ze.GL_ALPHA_EQUATION_MAX,Ze.GL_ALPHA_EQUATION_MAX);break;case Ze.ALPHA_EQUATION_MIN:this._alphaState.setAlphaEquationParameters(Ze.GL_ALPHA_EQUATION_MIN,Ze.GL_ALPHA_EQUATION_MIN);break;case Ze.ALPHA_EQUATION_DARKEN:this._alphaState.setAlphaEquationParameters(Ze.GL_ALPHA_EQUATION_MIN,Ze.GL_ALPHA_EQUATION_ADD)}this._alphaEquation=e}},vt.prototype.getInputElement=function(){return this._renderingCanvas},vt.prototype.getDepthFunction=function(){return this._depthCullingState.depthFunc},vt.prototype.setDepthFunction=function(e){this._depthCullingState.depthFunc=e},vt.prototype.setDepthFunctionToGreater=function(){this.setDepthFunction(Ze.GREATER)},vt.prototype.setDepthFunctionToGreaterOrEqual=function(){this.setDepthFunction(Ze.GEQUAL)},vt.prototype.setDepthFunctionToLess=function(){this.setDepthFunction(Ze.LESS)},vt.prototype.setDepthFunctionToLessOrEqual=function(){this.setDepthFunction(Ze.LEQUAL)},vt.prototype.getDepthWrite=function(){return this._depthCullingState.depthMask},vt.prototype.setDepthWrite=function(e){this._depthCullingState.depthMask=e},vt.prototype.getStencilBuffer=function(){return this._stencilState.stencilTest},vt.prototype.setStencilBuffer=function(e){this._stencilState.stencilTest=e},vt.prototype.getStencilMask=function(){return this._stencilState.stencilMask},vt.prototype.setStencilMask=function(e){this._stencilState.stencilMask=e},vt.prototype.getStencilFunction=function(){return this._stencilState.stencilFunc},vt.prototype.getStencilFunctionReference=function(){return this._stencilState.stencilFuncRef},vt.prototype.getStencilFunctionMask=function(){return this._stencilState.stencilFuncMask},vt.prototype.setStencilFunction=function(e){this._stencilState.stencilFunc=e},vt.prototype.setStencilFunctionReference=function(e){this._stencilState.stencilFuncRef=e},vt.prototype.setStencilFunctionMask=function(e){this._stencilState.stencilFuncMask=e},vt.prototype.getStencilOperationFail=function(){return this._stencilState.stencilOpStencilFail},vt.prototype.getStencilOperationDepthFail=function(){return this._stencilState.stencilOpDepthFail},vt.prototype.getStencilOperationPass=function(){return this._stencilState.stencilOpStencilDepthPass},vt.prototype.setStencilOperationFail=function(e){this._stencilState.stencilOpStencilFail=e},vt.prototype.setStencilOperationDepthFail=function(e){this._stencilState.stencilOpDepthFail=e},vt.prototype.setStencilOperationPass=function(e){this._stencilState.stencilOpStencilDepthPass=e},vt.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()},vt.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)},vt.prototype.setAlphaConstants=function(e,t,i,n){this._alphaState.setAlphaBlendConstants(e,t,i,n)},vt.prototype.getAlphaMode=function(){return this._alphaMode},vt.prototype.getAlphaEquation=function(){return this._alphaEquation},vt.prototype.getRenderPassNames=function(){return this._renderPassNames},vt.prototype.getCurrentRenderPassName=function(){return this._renderPassNames[this.currentRenderPassId]},vt.prototype.createRenderPassId=function(e){const t=++vt._RenderPassIdCounter;return this._renderPassNames[t]=e??"NONAME",t},vt.prototype.releaseRenderPassId=function(e){this._renderPassNames[e]=void 0;for(let t=0;t<this.scenes.length;++t){const i=this.scenes[t];for(let t=0;t<i.meshes.length;++t){const n=i.meshes[t];if(n.subMeshes)for(let t=0;t<n.subMeshes.length;++t){n.subMeshes[t]._removeDrawWrapper(e)}}}},vt.AudioEngineFactory=(e,t,i)=>new Md(e,t,i);class Md{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 g,this.onAudioLockedObservable=new g,this._tryToRun=!1,this._onResize=()=>{this._moveButtonToTopLeft()},!oe())return;void 0!==window.AudioContext&&(this.canUseWebAudio=!0);const n=document.createElement("audio");this._hostElement=e,this._audioContext=t,this._audioDestination=i;try{n&&n.canPlayType&&(n.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/,"")||n.canPlayType("audio/mp3").replace(/^no$/,""))&&(this.isMP3supported=!0)}catch(e){}try{n&&n.canPlayType&&n.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,de.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 xd extends Ni{static get NpmPackage(){return vt.NpmPackage}static get Version(){return vt.Version}static get Instances(){return y.Instances}static get LastCreatedEngine(){return y.LastCreatedEngine}static get LastCreatedScene(){return y.LastCreatedScene}static DefaultLoadingScreenFactory(e){return vt.DefaultLoadingScreenFactory(e)}get _supportsHardwareTextureRescaling(){return!!xd._RescalePostProcessFactory}_measureFps(){this._performanceMonitor.sampleFrame(),this._fps=this._performanceMonitor.averageFPS,this._deltaTime=this._performanceMonitor.instantaneousFrameTime||0}get performanceMonitor(){return this._performanceMonitor}constructor(e,t,i,n=!1){if(super(e,t,i,n),this.customAnimationFrameRequester=null,this._performanceMonitor=new Sd,this._drawCalls=new gr,e&&(this._features.supportRenderPasses=!0,i=this._creationOptions,e.getContext)){const t=e;this._sharedInit(t)}}_initGLContext(){super._initGLContext(),this._rescalePostProcess=null}_sharedInit(e){super._sharedInit(e),function(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 n=e.getHostWindow();n&&"function"==typeof n.addEventListener&&(n.addEventListener("blur",e._onBlur),n.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),!vt.audioEngine&&i.audioEngine&&vt.AudioEngineFactory&&(vt.audioEngine=vt.AudioEngineFactory(e.getRenderingCanvas(),e.getAudioContext(),e.getAudioDestination())),ce()&&(e._onFullscreenChange=()=>{e.isFullscreen=!!document.fullscreenElement,e.isFullscreen&&e._pointerLockRequested&&t&&Cd(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!==vt.OfflineProviderFactory,e._deterministicLockstep=!!i.deterministicLockstep,e._lockstepMaxSteps=i.lockstepMaxSteps||0,e._timeStep=i.timeStep||1/60}(this,e,this._creationOptions)}resizeImageBitmap(e,t,i){return function(e,t,i,n){const r=e.createCanvas(i,n).getContext("2d");if(!r)throw new Error("Unable to get 2d context for resizeImageBitmap");return r.drawImage(t,0,0),r.getImageData(0,0,i,n).data}(this,e,t,i)}_createImageBitmapFromSource(e,t){return function(e,t,i){return new Promise(((n,r)=>{const s=new Image;s.onload=()=>{s.decode().then((()=>{e.createImageBitmap(s,i).then((e=>{n(e)}))}))},s.onerror=()=>{r(`Error loading image ${s.src}`)},s.src=t}))}(this,e,t)}switchFullscreen(e){this.isFullscreen?this.exitFullscreen():this.enterFullscreen(e)}enterFullscreen(e){this.isFullscreen||(this._pointerLockRequested=e,this._renderingCanvas&&function(e){const t=e.requestFullscreen||e.webkitRequestFullscreen;t&&t.call(e)}(this._renderingCanvas))}exitFullscreen(){this.isFullscreen&&function(){const e=document;document.exitFullscreen?document.exitFullscreen():e.webkitCancelFullScreen&&e.webkitCancelFullScreen()}()}setDitheringState(e){e?this._gl.enable(this._gl.DITHER):this._gl.disable(this._gl.DITHER)}setRasterizerState(e){e?this._gl.disable(this._gl.RASTERIZER_DISCARD):this._gl.enable(this._gl.RASTERIZER_DISCARD)}setDirectViewport(e,t,i,n){const r=this._cachedViewport;return this._cachedViewport=null,this._viewport(e,t,i,n),r}scissorClear(e,t,i,n,r){this.enableScissor(e,t,i,n),this.clear(r,!0,!0,!0),this.disableScissor()}enableScissor(e,t,i,n){const r=this._gl;r.enable(r.SCISSOR_TEST),r.scissor(e,t,i,n)}disableScissor(){const e=this._gl;e.disable(e.SCISSOR_TEST)}_loadFileAsync(e,t,i){return new Promise(((n,r)=>{this._loadFile(e,(e=>{n(e)}),void 0,t,i,((e,t)=>{r(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 function(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 n=document.createElement("div");n.style.whiteSpace="nowrap",n.appendChild(t),n.appendChild(i),document.body.appendChild(n);let r=0,s=0;try{s=i.getBoundingClientRect().top-t.getBoundingClientRect().top,i.style.verticalAlign="baseline",r=i.getBoundingClientRect().top-t.getBoundingClientRect().top}finally{document.body.removeChild(n)}return{ascent:r,height:s,descent:s-r}}(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&&Cd(this._renderingCanvas)}exitPointerlock(){document.exitPointerLock&&document.exitPointerLock()}beginFrame(){this._measureFps(),super.beginFrame()}_deletePipelineContext(e){const t=e;t&&t.program&&t.transformFeedback&&(this.deleteTransformFeedback(t.transformFeedback),t.transformFeedback=null),super._deletePipelineContext(e)}createShaderProgram(e,t,i,n,r,s=null){r=r||this._gl,this.onBeforeShaderCompilationObservable.notifyObservers(this);const a=super.createShaderProgram(e,t,i,n,r,s);return this.onAfterShaderCompilationObservable.notifyObservers(this),a}_createShaderProgram(e,t,i,n,r=null){const s=n.createProgram();if(e.program=s,!s)throw new Error("Unable to create program");if(n.attachShader(s,t),n.attachShader(s,i),this.webGLVersion>1&&r){const t=this.createTransformFeedback();this.bindTransformFeedback(t),this.setTranformFeedbackVaryings(s,r),e.transformFeedback=t}return n.linkProgram(s),this.webGLVersion>1&&r&&this.bindTransformFeedback(null),e.context=n,e.vertexShader=t,e.fragmentShader=i,e.isParallelCompiled||this._finalizePipelineContext(e),s}_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,n,r){this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MAG_FILTER,this._gl.LINEAR),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MIN_FILTER,this._gl.LINEAR),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_S,this._gl.CLAMP_TO_EDGE),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_T,this._gl.CLAMP_TO_EDGE);const s=this.createRenderTargetTexture({width:t.width,height:t.height},{generateMipMaps:!1,type:Ze.TEXTURETYPE_UNSIGNED_INT,samplingMode:Ze.TEXTURE_BILINEAR_SAMPLINGMODE,generateDepthBuffer:!1,generateStencilBuffer:!1});if(!this._rescalePostProcess&&xd._RescalePostProcessFactory&&(this._rescalePostProcess=xd._RescalePostProcessFactory(this)),this._rescalePostProcess){this._rescalePostProcess.externalTextureSamplerBinding=!0;const a=()=>{this._rescalePostProcess.onApply=function(t){t._bindTexture("textureSampler",e)};let a=i;a||(a=this.scenes[this.scenes.length-1]),a.postProcessManager.directRender([this._rescalePostProcess],s,!0),this._bindTextureDirectly(this._gl.TEXTURE_2D,t,!0),this._gl.copyTexImage2D(this._gl.TEXTURE_2D,0,n,0,0,t.width,t.height,0),this.unBindFramebuffer(s),s.dispose(),r&&r()},o=this._rescalePostProcess.getEffect();o?o.executeWhenCompiled(a):this._rescalePostProcess.onEffectCreatedObservable.addOnce((e=>{e.executeWhenCompiled(a)}))}}wrapWebGLTexture(e,t=!1,i=Ze.TEXTURE_TRILINEAR_SAMPLINGMODE,n=0,r=0){const s=new Oi(e,this._gl),a=new Et(this,0,!0);return a._hardwareTexture=s,a.baseWidth=n,a.baseHeight=r,a.width=n,a.height=r,a.isReady=!0,a.useMipMaps=t,this.updateTextureSamplingMode(i,a),a}_uploadImageToTexture(e,t,i=0,n=0){const r=this._gl,s=this._getWebGLTextureType(e.type),a=this._getInternalFormat(e.format),o=this._getRGBABufferInternalSizedFormat(e.type,a),l=e.isCube?r.TEXTURE_CUBE_MAP:r.TEXTURE_2D;this._bindTextureDirectly(l,e,!0),this._unpackFlipY(e.invertY);let c=r.TEXTURE_2D;e.isCube&&(c=r.TEXTURE_CUBE_MAP_POSITIVE_X+i),r.texImage2D(c,n,o,a,s,t),this._bindTextureDirectly(l,null,!0)}updateTextureComparisonFunction(e,t){if(1===this.webGLVersion)return void de.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,Ze.LEQUAL),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,Ze.LEQUAL),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 yi(t);return i.capacity=e,this.bindArrayBuffer(i),this._gl.bufferData(this._gl.ARRAY_BUFFER,e,this._gl.DYNAMIC_DRAW),i.references=1,i}deleteInstancesBuffer(e){this._gl.deleteBuffer(e)}_clientWaitAsync(e,t=0,i=10){const n=this._gl;return new Promise(((r,s)=>{const a=()=>{const o=n.clientWaitSync(e,t,0);o!=n.WAIT_FAILED?o!=n.TIMEOUT_EXPIRED?r():setTimeout(a,i):s()};a()}))}_readPixelsAsync(e,t,i,n,r,s,a){if(this._webGLVersion<2)throw new Error("_readPixelsAsync only work on WebGL2+");const o=this._gl,l=o.createBuffer();o.bindBuffer(o.PIXEL_PACK_BUFFER,l),o.bufferData(o.PIXEL_PACK_BUFFER,a.byteLength,o.STREAM_READ),o.readPixels(e,t,i,n,r,s,0),o.bindBuffer(o.PIXEL_PACK_BUFFER,null);const c=o.fenceSync(o.SYNC_GPU_COMMANDS_COMPLETE,0);return c?(o.flush(),this._clientWaitAsync(c,0,10).then((()=>(o.deleteSync(c),o.bindBuffer(o.PIXEL_PACK_BUFFER,l),o.getBufferSubData(o.PIXEL_PACK_BUFFER,0,a),o.bindBuffer(o.PIXEL_PACK_BUFFER,null),o.deleteBuffer(l),a)))):null}dispose(){this.hideLoadingUI(),this._rescalePostProcess&&this._rescalePostProcess.dispose(),function(e,t){1===y.Instances.length&&vt.audioEngine&&(vt.audioEngine.dispose(),vt.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)),ce()&&(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))}(this,this._renderingCanvas),super.dispose()}}xd.ALPHA_DISABLE=Ze.ALPHA_DISABLE,xd.ALPHA_ADD=Ze.ALPHA_ADD,xd.ALPHA_COMBINE=Ze.ALPHA_COMBINE,xd.ALPHA_SUBTRACT=Ze.ALPHA_SUBTRACT,xd.ALPHA_MULTIPLY=Ze.ALPHA_MULTIPLY,xd.ALPHA_MAXIMIZED=Ze.ALPHA_MAXIMIZED,xd.ALPHA_ONEONE=Ze.ALPHA_ONEONE,xd.ALPHA_PREMULTIPLIED=Ze.ALPHA_PREMULTIPLIED,xd.ALPHA_PREMULTIPLIED_PORTERDUFF=Ze.ALPHA_PREMULTIPLIED_PORTERDUFF,xd.ALPHA_INTERPOLATE=Ze.ALPHA_INTERPOLATE,xd.ALPHA_SCREENMODE=Ze.ALPHA_SCREENMODE,xd.DELAYLOADSTATE_NONE=Ze.DELAYLOADSTATE_NONE,xd.DELAYLOADSTATE_LOADED=Ze.DELAYLOADSTATE_LOADED,xd.DELAYLOADSTATE_LOADING=Ze.DELAYLOADSTATE_LOADING,xd.DELAYLOADSTATE_NOTLOADED=Ze.DELAYLOADSTATE_NOTLOADED,xd.NEVER=Ze.NEVER,xd.ALWAYS=Ze.ALWAYS,xd.LESS=Ze.LESS,xd.EQUAL=Ze.EQUAL,xd.LEQUAL=Ze.LEQUAL,xd.GREATER=Ze.GREATER,xd.GEQUAL=Ze.GEQUAL,xd.NOTEQUAL=Ze.NOTEQUAL,xd.KEEP=Ze.KEEP,xd.REPLACE=Ze.REPLACE,xd.INCR=Ze.INCR,xd.DECR=Ze.DECR,xd.INVERT=Ze.INVERT,xd.INCR_WRAP=Ze.INCR_WRAP,xd.DECR_WRAP=Ze.DECR_WRAP,xd.TEXTURE_CLAMP_ADDRESSMODE=Ze.TEXTURE_CLAMP_ADDRESSMODE,xd.TEXTURE_WRAP_ADDRESSMODE=Ze.TEXTURE_WRAP_ADDRESSMODE,xd.TEXTURE_MIRROR_ADDRESSMODE=Ze.TEXTURE_MIRROR_ADDRESSMODE,xd.TEXTUREFORMAT_ALPHA=Ze.TEXTUREFORMAT_ALPHA,xd.TEXTUREFORMAT_LUMINANCE=Ze.TEXTUREFORMAT_LUMINANCE,xd.TEXTUREFORMAT_LUMINANCE_ALPHA=Ze.TEXTUREFORMAT_LUMINANCE_ALPHA,xd.TEXTUREFORMAT_RGB=Ze.TEXTUREFORMAT_RGB,xd.TEXTUREFORMAT_RGBA=Ze.TEXTUREFORMAT_RGBA,xd.TEXTUREFORMAT_RED=Ze.TEXTUREFORMAT_RED,xd.TEXTUREFORMAT_R=Ze.TEXTUREFORMAT_R,xd.TEXTUREFORMAT_RG=Ze.TEXTUREFORMAT_RG,xd.TEXTUREFORMAT_RED_INTEGER=Ze.TEXTUREFORMAT_RED_INTEGER,xd.TEXTUREFORMAT_R_INTEGER=Ze.TEXTUREFORMAT_R_INTEGER,xd.TEXTUREFORMAT_RG_INTEGER=Ze.TEXTUREFORMAT_RG_INTEGER,xd.TEXTUREFORMAT_RGB_INTEGER=Ze.TEXTUREFORMAT_RGB_INTEGER,xd.TEXTUREFORMAT_RGBA_INTEGER=Ze.TEXTUREFORMAT_RGBA_INTEGER,xd.TEXTURETYPE_UNSIGNED_BYTE=Ze.TEXTURETYPE_UNSIGNED_BYTE,xd.TEXTURETYPE_UNSIGNED_INT=Ze.TEXTURETYPE_UNSIGNED_INT,xd.TEXTURETYPE_FLOAT=Ze.TEXTURETYPE_FLOAT,xd.TEXTURETYPE_HALF_FLOAT=Ze.TEXTURETYPE_HALF_FLOAT,xd.TEXTURETYPE_BYTE=Ze.TEXTURETYPE_BYTE,xd.TEXTURETYPE_SHORT=Ze.TEXTURETYPE_SHORT,xd.TEXTURETYPE_UNSIGNED_SHORT=Ze.TEXTURETYPE_UNSIGNED_SHORT,xd.TEXTURETYPE_INT=Ze.TEXTURETYPE_INT,xd.TEXTURETYPE_UNSIGNED_INTEGER=Ze.TEXTURETYPE_UNSIGNED_INTEGER,xd.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=Ze.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4,xd.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=Ze.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1,xd.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=Ze.TEXTURETYPE_UNSIGNED_SHORT_5_6_5,xd.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=Ze.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV,xd.TEXTURETYPE_UNSIGNED_INT_24_8=Ze.TEXTURETYPE_UNSIGNED_INT_24_8,xd.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=Ze.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV,xd.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=Ze.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV,xd.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=Ze.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV,xd.TEXTURE_NEAREST_SAMPLINGMODE=Ze.TEXTURE_NEAREST_SAMPLINGMODE,xd.TEXTURE_BILINEAR_SAMPLINGMODE=Ze.TEXTURE_BILINEAR_SAMPLINGMODE,xd.TEXTURE_TRILINEAR_SAMPLINGMODE=Ze.TEXTURE_TRILINEAR_SAMPLINGMODE,xd.TEXTURE_NEAREST_NEAREST_MIPLINEAR=Ze.TEXTURE_NEAREST_NEAREST_MIPLINEAR,xd.TEXTURE_LINEAR_LINEAR_MIPNEAREST=Ze.TEXTURE_LINEAR_LINEAR_MIPNEAREST,xd.TEXTURE_LINEAR_LINEAR_MIPLINEAR=Ze.TEXTURE_LINEAR_LINEAR_MIPLINEAR,xd.TEXTURE_NEAREST_NEAREST_MIPNEAREST=Ze.TEXTURE_NEAREST_NEAREST_MIPNEAREST,xd.TEXTURE_NEAREST_LINEAR_MIPNEAREST=Ze.TEXTURE_NEAREST_LINEAR_MIPNEAREST,xd.TEXTURE_NEAREST_LINEAR_MIPLINEAR=Ze.TEXTURE_NEAREST_LINEAR_MIPLINEAR,xd.TEXTURE_NEAREST_LINEAR=Ze.TEXTURE_NEAREST_LINEAR,xd.TEXTURE_NEAREST_NEAREST=Ze.TEXTURE_NEAREST_NEAREST,xd.TEXTURE_LINEAR_NEAREST_MIPNEAREST=Ze.TEXTURE_LINEAR_NEAREST_MIPNEAREST,xd.TEXTURE_LINEAR_NEAREST_MIPLINEAR=Ze.TEXTURE_LINEAR_NEAREST_MIPLINEAR,xd.TEXTURE_LINEAR_LINEAR=Ze.TEXTURE_LINEAR_LINEAR,xd.TEXTURE_LINEAR_NEAREST=Ze.TEXTURE_LINEAR_NEAREST,xd.TEXTURE_EXPLICIT_MODE=Ze.TEXTURE_EXPLICIT_MODE,xd.TEXTURE_SPHERICAL_MODE=Ze.TEXTURE_SPHERICAL_MODE,xd.TEXTURE_PLANAR_MODE=Ze.TEXTURE_PLANAR_MODE,xd.TEXTURE_CUBIC_MODE=Ze.TEXTURE_CUBIC_MODE,xd.TEXTURE_PROJECTION_MODE=Ze.TEXTURE_PROJECTION_MODE,xd.TEXTURE_SKYBOX_MODE=Ze.TEXTURE_SKYBOX_MODE,xd.TEXTURE_INVCUBIC_MODE=Ze.TEXTURE_INVCUBIC_MODE,xd.TEXTURE_EQUIRECTANGULAR_MODE=Ze.TEXTURE_EQUIRECTANGULAR_MODE,xd.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=Ze.TEXTURE_FIXED_EQUIRECTANGULAR_MODE,xd.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=Ze.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE,xd.SCALEMODE_FLOOR=Ze.SCALEMODE_FLOOR,xd.SCALEMODE_NEAREST=Ze.SCALEMODE_NEAREST,xd.SCALEMODE_CEILING=Ze.SCALEMODE_CEILING;const bd={engine:"WebGL"};function yd(e,t){const i={...bd,...t},n=[];let r=!1;const s=new ResizeObserver((()=>r=!0));s.observe(e),n.push((()=>s.disconnect()));const a=new xd(e,void 0,t),o=i.onInitialized;i.onInitialized=e=>{const t=e.scene.onBeforeRenderObservable.add((()=>{r&&(a.resize(),r=!1)}));n.push((()=>t.remove())),o?.(e)};const l=new Rd(a,i);return n.push(l.dispose.bind(l)),n.push((()=>a.dispose())),l.dispose=()=>n.forEach((e=>e())),l}class Od extends HTMLElement{constructor(){super();const e=this.attachShadow({mode:"open"});e.innerHTML='\n <style>\n :host {\n display: block;\n width: 100%;\n height: 100%;\n }\n\n #container {\n display: block;\n width: 100%;\n height: 100%;\n }\n\n #renderCanvas {\n width: 100%;\n height: 100%;\n display: block;\n font-size: 0;\n }\n </style>\n <div id="container">\n <canvas id="renderCanvas" touch-action="none"></canvas>\n </div>\n ';const t=e.querySelector("#renderCanvas");this.viewer=yd(t)}get src(){return this.getAttribute("src")}set src(e){null===e?this.removeAttribute("src"):this.setAttribute("src",e)}connectedCallback(){}attributeChangedCallback(e,t,i){switch(e){case"src":this.viewer.loadModelAsync(i).catch(de.Log);break;case"env":this.viewer.loadEnvironmentAsync(i).catch(de.Log)}}}Od.observedAttributes=Object.freeze(["src","env"]),globalThis.customElements.define("babylon-viewer",Od);var Dd,Nd=Object.freeze({__proto__:null,_DDSTextureLoader:class{constructor(){this.supportCascades=!0}loadCubeData(e,t,i,n){const r=t.getEngine();let s,a=!1,o=1e3;if(Array.isArray(e))for(let i=0;i<e.length;i++){const n=e[i];s=Zs.GetDDSInfo(n),t.width=s.width,t.height=s.height,a=(s.isRGB||s.isLuminance||s.mipmapCount>1)&&t.generateMipMaps,r._unpackFlipY(s.isCompressed),Zs.UploadDDSLevels(r,t,n,s,a,6,-1,i),s.isFourCC||1!==s.mipmapCount?o=s.mipmapCount-1:r.generateMipMapsForCubemap(t)}else{const n=e;s=Zs.GetDDSInfo(n),t.width=s.width,t.height=s.height,i&&(s.sphericalPolynomial=new Is),a=(s.isRGB||s.isLuminance||s.mipmapCount>1)&&t.generateMipMaps,r._unpackFlipY(s.isCompressed),Zs.UploadDDSLevels(r,t,n,s,a,6),s.isFourCC||1!==s.mipmapCount?o=s.mipmapCount-1:r.generateMipMapsForCubemap(t,!1)}r._setCubeMapTextureParams(t,a,o),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),n&&n({isDDS:!0,width:t.width,info:s,data:e,texture:t})}loadData(e,t,i){const n=Zs.GetDDSInfo(e),r=(n.isRGB||n.isLuminance||n.mipmapCount>1)&&t.generateMipMaps&&Math.max(n.width,n.height)>>n.mipmapCount-1==1;i(n.width,n.height,r,n.isFourCC,(()=>{Zs.UploadDDSLevels(t.getEngine(),t,e,n,r,1)}))}}});function Pd(){const e=0,t=1,i=2,n=3,r=6,s=8,a=9,o=10,l=14;let c=null;function h(e,t,i,n,r){const s=e.getImageTranscodedSizeInBytes(t,i,n);let a=new Uint8Array(s);if(!e.transcodeImage(a,t,i,n,1,0))return null;if(r){a=function(e,t,i,n){const r=new Uint16Array(4),s=new Uint16Array(i*n),a=i/4,o=n/4;for(let n=0;n<o;n++)for(let o=0;o<a;o++){const l=t+8*(n*a+o);r[0]=e[l]|e[l+1]<<8,r[1]=e[l+2]|e[l+3]<<8,r[2]=(2*(31&r[0])+1*(31&r[1]))/3|(2*(2016&r[0])+1*(2016&r[1]))/3&2016|(2*(63488&r[0])+1*(63488&r[1]))/3&63488,r[3]=(2*(31&r[1])+1*(31&r[0]))/3|(2*(2016&r[1])+1*(2016&r[0]))/3&2016|(2*(63488&r[1])+1*(63488&r[0]))/3&63488;for(let t=0;t<4;t++){const a=e[l+4+t];let c=(4*n+t)*i+4*o;s[c++]=r[3&a],s[c++]=r[a>>2&3],s[c++]=r[a>>4&3],s[c++]=r[a>>6&3]}}return s}(a,0,e.getImageWidth(t,i)+3&-4,e.getImageHeight(t,i)+3&-4)}return a}onmessage=d=>{if("init"===d.data.action){if(d.data.url)try{importScripts(d.data.url)}catch(e){postMessage({action:"error",error:e})}c||(c=BASIS({wasmBinary:d.data.wasmBinary})),null!==c&&c.then((e=>{BASIS=e,e.initializeBasis(),postMessage({action:"init"})}))}else if("transcode"===d.data.action){const c=d.data.config,u=d.data.imageData,f=new BASIS.BasisFile(u),_=function(e){const t=e.getHasAlpha(),i=e.getNumImages(),n=[];for(let t=0;t<i;t++){const i={levels:[]},r=e.getNumLevels(t);for(let n=0;n<r;n++){const r={width:e.getImageWidth(t,n),height:e.getImageHeight(t,n)};i.levels.push(r)}n.push(i)}return{hasAlpha:t,images:n}}(f);let m=d.data.ignoreSupportedFormats?null:function(c,h){let d=null;c.supportedCompressionFormats&&(d=c.supportedCompressionFormats.astc?o:c.supportedCompressionFormats.bc7?r:c.supportedCompressionFormats.s3tc?h.hasAlpha?n:i:c.supportedCompressionFormats.pvrtc?h.hasAlpha?a:s:c.supportedCompressionFormats.etc2?t:c.supportedCompressionFormats.etc1?e:l);return d}(d.data.config,_),p=!1;null===m&&(p=!0,m=_.hasAlpha?n:i);let g=!0;f.startTranscoding()||(g=!1);const E=[];for(let e=0;e<_.images.length&&g;e++){const t=_.images[e];if(void 0===c.loadSingleImage||c.loadSingleImage===e){let i=t.levels.length;!1===c.loadMipmapLevels&&(i=1);for(let n=0;n<i;n++){const i=t.levels[n],r=h(f,e,n,m,p);if(!r){g=!1;break}i.transcodedPixels=r,E.push(i.transcodedPixels.buffer)}}}f.close(),f.delete(),p&&(m=-1),g?postMessage({action:"transcode",success:g,id:d.data.id,fileInfo:_,format:m},E):postMessage({action:"transcode",success:g,id:d.data.id})}}}!function(e){e[e.cTFETC1=0]="cTFETC1",e[e.cTFETC2=1]="cTFETC2",e[e.cTFBC1=2]="cTFBC1",e[e.cTFBC3=3]="cTFBC3",e[e.cTFBC4=4]="cTFBC4",e[e.cTFBC5=5]="cTFBC5",e[e.cTFBC7=6]="cTFBC7",e[e.cTFPVRTC1_4_RGB=8]="cTFPVRTC1_4_RGB",e[e.cTFPVRTC1_4_RGBA=9]="cTFPVRTC1_4_RGBA",e[e.cTFASTC_4x4=10]="cTFASTC_4x4",e[e.cTFATC_RGB=11]="cTFATC_RGB",e[e.cTFATC_RGBA_INTERPOLATED_ALPHA=12]="cTFATC_RGBA_INTERPOLATED_ALPHA",e[e.cTFRGBA32=13]="cTFRGBA32",e[e.cTFRGB565=14]="cTFRGB565",e[e.cTFBGR565=15]="cTFBGR565",e[e.cTFRGBA4444=16]="cTFRGBA4444",e[e.cTFFXT1_RGB=17]="cTFFXT1_RGB",e[e.cTFPVRTC2_4_RGB=18]="cTFPVRTC2_4_RGB",e[e.cTFPVRTC2_4_RGBA=19]="cTFPVRTC2_4_RGBA",e[e.cTFETC2_EAC_R11=20]="cTFETC2_EAC_R11",e[e.cTFETC2_EAC_RG11=21]="cTFETC2_EAC_RG11"}(Dd||(Dd={}));const Ld={JSModuleURL:`${Yt._DefaultCdnUrl}/basisTranscoder/1/basis_transcoder.js`,WasmModuleURL:`${Yt._DefaultCdnUrl}/basisTranscoder/1/basis_transcoder.wasm`};let Fd=null,wd=null,Ud=0;const Bd=()=>(Fd||(Fd=new Promise(((e,t)=>{wd?e(wd):Yt.LoadFileAsync(Yt.GetBabylonScriptURL(Ld.WasmModuleURL)).then((i=>{if("function"!=typeof URL)return t("Basis transcoder requires an environment with a URL constructor");const n=URL.createObjectURL(new Blob([`(${Pd})()`],{type:"application/javascript"}));wd=new Worker(n),function(e,t,i){return new Promise(((n,r)=>{const s=t=>{"init"===t.data.action?(e.removeEventListener("message",s),n(e)):"error"===t.data.action&&r(t.data.error||"error initializing worker")};e.addEventListener("message",s),e.postMessage({action:"init",url:i?Yt.GetBabylonScriptURL(i):void 0,wasmBinary:t},[t])}))}(wd,i,Ld.JSModuleURL).then(e,t)})).catch(t)}))),Fd),Gd=(e,t)=>{const i=e instanceof ArrayBuffer?new Uint8Array(e):e;return new Promise(((e,n)=>{Bd().then((()=>{const r=Ud++,s=t=>{"transcode"===t.data.action&&t.data.id===r&&(wd.removeEventListener("message",s),t.data.success?e(t.data):n("Transcode is not supported on this device"))};wd.addEventListener("message",s);const a=new Uint8Array(i.byteLength);a.set(new Uint8Array(i.buffer,i.byteOffset,i.byteLength)),wd.postMessage({action:"transcode",id:r,imageData:a,config:t,ignoreSupportedFormats:false},[a.buffer])}),(e=>{n(e)}))}))},Vd=(e,t)=>{let i=t._gl?.TEXTURE_2D;e.isCube&&(i=t._gl?.TEXTURE_CUBE_MAP),t._bindTextureDirectly(i,e,!0)},kd=(e,t)=>{const i=e.getEngine();for(let n=0;n<t.fileInfo.images.length;n++){const r=t.fileInfo.images[n].levels[0];if(e._invertVScale=e.invertY,-1===t.format||t.format===Dd.cTFRGB565)if(e.type=Ze.TEXTURETYPE_UNSIGNED_SHORT_5_6_5,e.format=Ze.TEXTUREFORMAT_RGB,!i._features.basisNeedsPOT||j.Log2(r.width)%1==0&&j.Log2(r.height)%1==0)e._invertVScale=!e.invertY,e.width=r.width+3&-4,e.height=r.height+3&-4,e.samplingMode=Ze.TEXTURE_LINEAR_LINEAR,Vd(e,i),i._uploadDataToTextureDirectly(e,new Uint16Array(r.transcodedPixels.buffer),n,0,Ze.TEXTUREFORMAT_RGB,!0);else{const t=new Et(i,2);e._invertVScale=e.invertY,t.type=Ze.TEXTURETYPE_UNSIGNED_SHORT_5_6_5,t.format=Ze.TEXTUREFORMAT_RGB,t.width=r.width+3&-4,t.height=r.height+3&-4,Vd(t,i),i._uploadDataToTextureDirectly(t,new Uint16Array(r.transcodedPixels.buffer),n,0,Ze.TEXTUREFORMAT_RGB,!0),i._rescaleTexture(t,e,i.scenes[0],i._getInternalFormat(Ze.TEXTUREFORMAT_RGB),(()=>{i._releaseTexture(t),Vd(e,i)}))}else{e.width=r.width,e.height=r.height,e.generateMipMaps=t.fileInfo.images[n].levels.length>1;const s=Xd.GetInternalFormatFromBasisFormat(t.format,i);e.format=s,Vd(e,i),t.fileInfo.images[n].levels.forEach(((t,r)=>{i._uploadCompressedDataToTextureDirectly(e,s,t.width,t.height,t.transcodedPixels,n,r)})),!i._features.basisNeedsPOT||j.Log2(e.width)%1==0&&j.Log2(e.height)%1==0||(Yt.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=Pr.CLAMP_ADDRESSMODE,e._cachedWrapV=Pr.CLAMP_ADDRESSMODE)}}},Xd={JSModuleURL:Ld.JSModuleURL,WasmModuleURL:Ld.WasmModuleURL,GetInternalFormatFromBasisFormat:(e,t)=>{let i;switch(e){case Dd.cTFETC1:i=Ze.TEXTUREFORMAT_COMPRESSED_RGB_ETC1_WEBGL;break;case Dd.cTFBC1:i=Ze.TEXTUREFORMAT_COMPRESSED_RGB_S3TC_DXT1;break;case Dd.cTFBC4:i=Ze.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT5;break;case Dd.cTFASTC_4x4:i=Ze.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_4x4;break;case Dd.cTFETC2:i=Ze.TEXTUREFORMAT_COMPRESSED_RGBA8_ETC2_EAC;break;case Dd.cTFBC7:i=Ze.TEXTUREFORMAT_COMPRESSED_RGBA_BPTC_UNORM}if(void 0===i)throw"The chosen Basis transcoder format is not currently supported";return i},TranscodeAsync:Gd,LoadTextureFromTranscodeResult:kd};Object.defineProperty(Xd,"JSModuleURL",{get:function(){return Ld.JSModuleURL},set:function(e){Ld.JSModuleURL=e}}),Object.defineProperty(Xd,"WasmModuleURL",{get:function(){return Ld.WasmModuleURL},set:function(e){Ld.WasmModuleURL=e}});var Hd=Object.freeze({__proto__:null,_BasisTextureLoader:class{constructor(){this.supportCascades=!1}loadCubeData(e,t,i,n,r){if(Array.isArray(e))return;const s=t.getEngine().getCaps(),a={supportedCompressionFormats:{etc1:!!s.etc1,s3tc:!!s.s3tc,pvrtc:!!s.pvrtc,etc2:!!s.etc2,astc:!!s.astc,bc7:!!s.bptc}};Gd(e,a).then((e=>{const i=e.fileInfo.images[0].levels.length>1&&t.generateMipMaps;kd(t,e),t.getEngine()._setCubeMapTextureParams(t,i),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),n&&n()})).catch((e=>{Yt.Warn("Failed to transcode Basis file, transcoding may not be supported on this device"),t.isReady=!0,r&&r(e)}))}loadData(e,t,i){const n=t.getEngine().getCaps(),r={supportedCompressionFormats:{etc1:!!n.etc1,s3tc:!!n.s3tc,pvrtc:!!n.pvrtc,etc2:!!n.etc2,astc:!!n.astc,bc7:!!n.bptc}};Gd(e,r).then((e=>{const n=e.fileInfo.images[0].levels[0],r=e.fileInfo.images[0].levels.length>1&&t.generateMipMaps;i(n.width,n.height,r,-1!==e.format,(()=>{kd(t,e)}))})).catch((e=>{Yt.Warn("Failed to transcode Basis file, transcoding may not be supported on this device"),Yt.Warn(`Failed to transcode Basis file: ${e}`),i(0,0,!1,!1,(()=>{}),!0)}))}}});function Wd(e,t,i,n,r,s){r>0?(r=function(e,t){return t>1023?e*Math.pow(2,1023)*Math.pow(2,t-1023):t<-1074?e*Math.pow(2,-1074)*Math.pow(2,t+1074):e*Math.pow(2,t)}(1,r-136),e[s+0]=t*r,e[s+1]=i*r,e[s+2]=n*r):(e[s+0]=0,e[s+1]=0,e[s+2]=0)}function zd(e,t){let i="",n="";for(let r=t;r<e.length-t&&(n=String.fromCharCode(e[r]),"\n"!=n);r++)i+=n;return i}function Yd(e,t){return function(e,t){let i=t.height;const n=t.width;let r,s,a,o,l,c=t.dataPosition,h=0,d=0,u=0;const f=new ArrayBuffer(4*n),_=new Uint8Array(f),m=new ArrayBuffer(t.width*t.height*4*3),p=new Float32Array(m);for(;i>0;){if(r=e[c++],s=e[c++],a=e[c++],o=e[c++],2!=r||2!=s||128&a||t.width<8||t.width>32767)return Kd(e,t);if((a<<8|o)!=n)throw"HDR Bad header format, wrong scan line width";for(h=0,u=0;u<4;u++)for(d=(u+1)*n;h<d;)if(r=e[c++],s=e[c++],r>128){if(l=r-128,0==l||l>d-h)throw"HDR Bad Format, bad scanline data (run)";for(;l-- >0;)_[h++]=s}else{if(l=r,0==l||l>d-h)throw"HDR Bad Format, bad scanline data (non-run)";if(_[h++]=s,--l>0)for(let t=0;t<l;t++)_[h++]=e[c++]}for(u=0;u<n;u++)r=_[u],s=_[u+n],a=_[u+2*n],o=_[u+3*n],Wd(p,r,s,a,o,(t.height-i)*n*3+3*u);i--}return p}(e,t)}function Kd(e,t){let i=t.height;const n=t.width;let r,s,a,o,l,c=t.dataPosition;const h=new ArrayBuffer(t.width*t.height*4*3),d=new Float32Array(h);for(;i>0;){for(l=0;l<t.width;l++)r=e[c++],s=e[c++],a=e[c++],o=e[c++],Wd(d,r,s,a,o,(t.height-i)*n*3+3*l);i--}return d}var qd,jd,Qd,Zd=Object.freeze({__proto__:null,_HDRTextureLoader:class{constructor(){this.supportCascades=!1}loadCubeData(){throw".env not supported in Cube."}loadData(e,t,i){const n=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),r=function(e){let t=0,i=0,n=zd(e,0);if("#"!=n[0]||"?"!=n[1])throw"Bad HDR Format.";let r=!1,s=!1,a=0;do{a+=n.length+1,n=zd(e,a),"FORMAT=32-bit_rle_rgbe"==n?s=!0:0==n.length&&(r=!0)}while(!r);if(!s)throw"HDR Bad header format, unsupported FORMAT";a+=n.length+1,n=zd(e,a);const o=/^-Y (.*) \+X (.*)$/g.exec(n);if(!o||o.length<3)throw"HDR Bad header format, no size";if(i=parseInt(o[2]),t=parseInt(o[1]),i<8||i>32767)throw"HDR Bad header format, unsupported size";return a+=n.length+1,{height:t,width:i,dataPosition:a}}(n),s=Yd(n,r),a=r.width*r.height,o=new Float32Array(4*a);for(let e=0;e<a;e+=1)o[4*e]=s[3*e],o[4*e+1]=s[3*e+1],o[4*e+2]=s[3*e+2],o[4*e+3]=1;i(r.width,r.height,t.generateMipMaps,!1,(()=>{const e=t.getEngine();t.type=Ze.TEXTURETYPE_FLOAT,t.format=Ze.TEXTUREFORMAT_RGBA,t._gammaSpace=!1,e._uploadDataToTextureDirectly(t,o)}))}}});class Jd{constructor(e,t){if(this.data=e,this.isInvalid=!1,!Jd.IsValid(e))return this.isInvalid=!0,void de.Error("texture missing KTX identifier");const i=Uint32Array.BYTES_PER_ELEMENT,n=new DataView(this.data.buffer,this.data.byteOffset+12,13*i),r=67305985===n.getUint32(0,!0);return this.glType=n.getUint32(1*i,r),this.glTypeSize=n.getUint32(2*i,r),this.glFormat=n.getUint32(3*i,r),this.glInternalFormat=n.getUint32(4*i,r),this.glBaseInternalFormat=n.getUint32(5*i,r),this.pixelWidth=n.getUint32(6*i,r),this.pixelHeight=n.getUint32(7*i,r),this.pixelDepth=n.getUint32(8*i,r),this.numberOfArrayElements=n.getUint32(9*i,r),this.numberOfFaces=n.getUint32(10*i,r),this.numberOfMipmapLevels=n.getUint32(11*i,r),this.bytesOfKeyValueData=n.getUint32(12*i,r),0!==this.glType?(de.Error("only compressed formats currently supported"),void(this.isInvalid=!0)):(this.numberOfMipmapLevels=Math.max(1,this.numberOfMipmapLevels),0===this.pixelHeight||0!==this.pixelDepth?(de.Error("only 2D textures currently supported"),void(this.isInvalid=!0)):0!==this.numberOfArrayElements?(de.Error("texture arrays not currently supported"),void(this.isInvalid=!0)):this.numberOfFaces!==t?(de.Error("number of faces expected"+t+", but found "+this.numberOfFaces),void(this.isInvalid=!0)):void(this.loadType=Jd.COMPRESSED_2D))}uploadLevels(e,t){if(this.loadType===Jd.COMPRESSED_2D)this._upload2DCompressedLevels(e,t)}_upload2DCompressedLevels(e,t){let i=Jd.HEADER_LEN+this.bytesOfKeyValueData,n=this.pixelWidth,r=this.pixelHeight;const s=t?this.numberOfMipmapLevels:1;for(let t=0;t<s;t++){const s=new Int32Array(this.data.buffer,this.data.byteOffset+i,1)[0];i+=4;for(let a=0;a<this.numberOfFaces;a++){const o=new Uint8Array(this.data.buffer,this.data.byteOffset+i,s);e.getEngine()._uploadCompressedDataToTextureDirectly(e,e.format,n,r,o,a,t),i+=s,i+=3-(s+3)%4}n=Math.max(1,.5*n),r=Math.max(1,.5*r)}}static IsValid(e){if(e.byteLength>=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}}function $d(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 eu(e){let t;void 0===e&&"undefined"!=typeof KTX2DECODER&&(e=KTX2DECODER),onmessage=i=>{if(i.data)switch(i.data.action){case"init":{const n=i.data.urls;n&&(n.jsDecoderModule&&void 0===e&&(importScripts(n.jsDecoderModule),e=KTX2DECODER),$d(n)),i.data.wasmBinaries&&$d(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<e.mipmaps.length;++i){const n=e.mipmaps[i];n&&n.data&&t.push(n.data.buffer)}postMessage({action:"decoded",success:!0,decodedData:e},t)})).catch((e=>{postMessage({action:"decoded",success:!1,msg:e})}))}}}Jd.HEADER_LEN=64,Jd.COMPRESSED_2D=0,Jd.COMPRESSED_3D=1,Jd.TEX_2D=2,Jd.TEX_3D=3,function(e){e[e.ETC1S=0]="ETC1S",e[e.UASTC4x4=1]="UASTC4x4"}(qd||(qd={})),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"}(jd||(jd={})),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"}(Qd||(Qd={}));class tu{static GetDefaultNumWorkers(){return"object"==typeof navigator&&navigator.hardwareConcurrency?Math.min(Math.floor(.5*navigator.hardwareConcurrency),4):1}static _Initialize(e){if(tu._WorkerPoolPromise||tu._DecoderModulePromise)return;const t={jsDecoderModule:Yt.GetBabylonScriptURL(this.URLConfig.jsDecoderModule,!0),wasmUASTCToASTC:Yt.GetBabylonScriptURL(this.URLConfig.wasmUASTCToASTC,!0),wasmUASTCToBC7:Yt.GetBabylonScriptURL(this.URLConfig.wasmUASTCToBC7,!0),wasmUASTCToRGBA_UNORM:Yt.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRGBA_UNORM,!0),wasmUASTCToRGBA_SRGB:Yt.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRGBA_SRGB,!0),wasmUASTCToR8_UNORM:Yt.GetBabylonScriptURL(this.URLConfig.wasmUASTCToR8_UNORM,!0),wasmUASTCToRG8_UNORM:Yt.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRG8_UNORM,!0),jsMSCTranscoder:Yt.GetBabylonScriptURL(this.URLConfig.jsMSCTranscoder,!0),wasmMSCTranscoder:Yt.GetBabylonScriptURL(this.URLConfig.wasmMSCTranscoder,!0),wasmZSTDDecoder:Yt.GetBabylonScriptURL(this.URLConfig.wasmZSTDDecoder,!0)};e&&"function"==typeof Worker&&"undefined"!=typeof URL?tu._WorkerPoolPromise=new Promise((i=>{const n=`${$d}(${eu})()`,r=URL.createObjectURL(new Blob([n],{type:"application/javascript"}));i(new Eo(e,(()=>function(e,t,i){return new Promise(((n,r)=>{const s=t=>{e.removeEventListener("error",s),e.removeEventListener("message",a),r(t)},a=t=>{"init"===t.data.action&&(e.removeEventListener("error",s),e.removeEventListener("message",a),n(e))};e.addEventListener("error",s),e.addEventListener("message",a),e.postMessage({action:"init",urls:i,wasmBinaries:t})}))}(new Worker(r),void 0,t))))})):void 0===tu._KTX2DecoderModule?tu._DecoderModulePromise=Yt.LoadBabylonScriptAsync(t.jsDecoderModule).then((()=>(tu._KTX2DecoderModule=KTX2DECODER,tu._KTX2DecoderModule.MSCTranscoder.UseFromWorkerThread=!1,tu._KTX2DecoderModule.WASMMemoryManager.LoadBinariesFromCurrentThread=!0,$d(t,tu._KTX2DecoderModule),new tu._KTX2DecoderModule.KTX2Decoder))):(tu._KTX2DecoderModule.MSCTranscoder.UseFromWorkerThread=!1,tu._KTX2DecoderModule.WASMMemoryManager.LoadBinariesFromCurrentThread=!0,tu._DecoderModulePromise=Promise.resolve(new tu._KTX2DecoderModule.KTX2Decoder))}constructor(e,t=tu.DefaultNumWorkers){this._engine=e;const i="object"==typeof t&&t.workerPool||tu.WorkerPool;if(i)tu._WorkerPoolPromise=Promise.resolve(i);else{"object"==typeof t?tu._KTX2DecoderModule=t?.binariesAndModulesContainer?.jsDecoderModule:"undefined"!=typeof KTX2DECODER&&(tu._KTX2DecoderModule=KTX2DECODER);const e="number"==typeof t?t:t.numWorkers??tu.DefaultNumWorkers;tu._Initialize(e)}}_uploadAsync(e,t,i){const n=this._engine.getCaps(),r={astc:!!n.astc,bptc:!!n.bptc,s3tc:!!n.s3tc,pvrtc:!!n.pvrtc,etc2:!!n.etc2,etc1:!!n.etc1};if(tu._WorkerPoolPromise)return tu._WorkerPoolPromise.then((n=>new Promise(((s,a)=>{n.push(((n,o)=>{const l=e=>{n.removeEventListener("error",l),n.removeEventListener("message",c),a(e),o()},c=e=>{if("decoded"===e.data.action){if(n.removeEventListener("error",l),n.removeEventListener("message",c),e.data.success)try{this._createTexture(e.data.decodedData,t,i),s()}catch(e){a({message:e})}else a({message:e.data.msg});o()}};n.addEventListener("error",l),n.addEventListener("message",c),n.postMessage({action:"setDefaultDecoderOptions",options:tu.DefaultDecoderOptions._getKTX2DecoderOptions()});const h=new Uint8Array(e.byteLength);h.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),n.postMessage({action:"decode",data:h,caps:r,options:i},[h.buffer])}))}))));if(tu._DecoderModulePromise)return tu._DecoderModulePromise.then((i=>(tu.DefaultDecoderOptions.isDirty&&(tu._KTX2DecoderModule.KTX2Decoder.DefaultDecoderOptions=tu.DefaultDecoderOptions._getKTX2DecoderOptions()),new Promise(((r,s)=>{i.decode(e,n).then((e=>{this._createTexture(e,t),r()})).catch((e=>{s({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 n=!0;switch(e.transcodedFormat){case 32856:t.type=Ze.TEXTURETYPE_UNSIGNED_BYTE,t.format=Ze.TEXTUREFORMAT_RGBA;break;case 33321:t.type=Ze.TEXTURETYPE_UNSIGNED_BYTE,t.format=Ze.TEXTUREFORMAT_R;break;case 33323:t.type=Ze.TEXTURETYPE_UNSIGNED_BYTE,t.format=Ze.TEXTUREFORMAT_RG;break;default:t.format=e.transcodedFormat,n=!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<e.mipmaps.length;++i){const r=e.mipmaps[i];if(!r||!r.data)throw new Error("KTX2 container - could not transcode one of the image");n?(t.width=r.width,t.height=r.height,this._engine._uploadDataToTextureDirectly(t,r.data,0,i,void 0,!0)):this._engine._uploadCompressedDataToTextureDirectly(t,e.transcodedFormat,r.width,r.height,r.data,0,i)}t._extension=".ktx2",t.width=e.mipmaps[0].width,t.height=e.mipmaps[0].height,t.isReady=!0,this._engine._bindTextureDirectly(3553,null)}static IsValid(e){if(e.byteLength>=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}}tu.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},tu.DefaultNumWorkers=tu.GetDefaultNumWorkers(),tu.DefaultDecoderOptions=new class{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:[jd.BC1_RGB,jd.BC3_RGBA],yes:{transcodeFormat:jd.RGBA32,engineFormat:32856,roundToMultiple4:!1}}}),this._ktx2DecoderOptions=e,e}};var iu=Object.freeze({__proto__:null,_KTXTextureLoader:class{constructor(){this.supportCascades=!1}loadCubeData(e,t,i,n){if(Array.isArray(e))return;t._invertVScale=!t.invertY;const r=t.getEngine(),s=new Jd(e,6),a=s.numberOfMipmapLevels>1&&t.generateMipMaps;r._unpackFlipY(!0),s.uploadLevels(t,t.generateMipMaps),t.width=s.pixelWidth,t.height=s.pixelHeight,r._setCubeMapTextureParams(t,a,s.numberOfMipmapLevels-1),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),n&&n()}loadData(e,t,i,n){if(Jd.IsValid(e)){t._invertVScale=!t.invertY;const n=new Jd(e,1),r=function(e){switch(e){case Ze.TEXTUREFORMAT_COMPRESSED_SRGB_S3TC_DXT1_EXT:return Ze.TEXTUREFORMAT_COMPRESSED_RGB_S3TC_DXT1;case Ze.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT:return Ze.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT3;case Ze.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT:return Ze.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT5;case Ze.TEXTUREFORMAT_COMPRESSED_SRGB8_ETC2:return Ze.TEXTUREFORMAT_COMPRESSED_RGB8_ETC2;case Ze.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:return Ze.TEXTUREFORMAT_COMPRESSED_RGBA8_ETC2_EAC;case Ze.TEXTUREFORMAT_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2:return Ze.TEXTUREFORMAT_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2;case Ze.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:return Ze.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_4x4;case Ze.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_BPTC_UNORM:return Ze.TEXTUREFORMAT_COMPRESSED_RGBA_BPTC_UNORM}return null}(n.glInternalFormat);r?(t.format=r,t._useSRGBBuffer=t.getEngine()._getUseSRGBBuffer(!0,t.generateMipMaps),t._gammaSpace=!0):t.format=n.glInternalFormat,i(n.pixelWidth,n.pixelHeight,t.generateMipMaps,!0,(()=>{n.uploadLevels(t,t.generateMipMaps)}),n.isInvalid)}else if(tu.IsValid(e)){new tu(t.getEngine())._uploadAsync(e,t,n).then((()=>{i(t.width,t.height,t.generateMipMaps,!0,(()=>{}),!1)}),(e=>{de.Warn(`Failed to load KTX2 texture data: ${e.message}`),i(0,0,!1,!1,(()=>{}),!0)}))}else de.Error("texture missing KTX identifier"),i(0,0,!1,!1,(()=>{}),!0)}}});function nu(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 ru(e,t){if(t.length<19)return void de.Error("Unable to load TGA file - Not enough data to contain header");let i=18;const n=nu(t);if(n.id_length+i>t.length)return void de.Error("Unable to load TGA file - Not enough data");i+=n.id_length;let r,s=!1,a=!1,o=!1;switch(n.image_type){case 9:s=!0;case 1:a=!0;break;case 10:s=!0;case 2:break;case 11:s=!0;case 3:o=!0}const l=n.pixel_size>>3,c=n.width*n.height*l;let h,d,u,f,_,m,p;if(a&&(h=t.subarray(i,i+=n.colormap_length*(n.colormap_size>>3))),s){let e,n,s;r=new Uint8Array(c);let a=0;const o=new Uint8Array(l);for(;i<c&&a<c;)if(e=t[i++],n=1+(127&e),128&e){for(s=0;s<l;++s)o[s]=t[i++];for(s=0;s<n;++s)r.set(o,a+s*l);a+=l*n}else{for(n*=l,s=0;s<n;++s)r[a+s]=t[i++];a+=n}}else r=t.subarray(i,i+=a?n.width*n.height:c);switch((48&n.flags)>>4){default:case 2:d=0,f=1,p=n.width,u=0,_=1,m=n.height;break;case 0:d=0,f=1,p=n.width,u=n.height-1,_=-1,m=-1;break;case 3:d=n.width-1,f=-1,p=-1,u=0,_=1,m=n.height;break;case 1:d=n.width-1,f=-1,p=-1,u=n.height-1,_=-1,m=-1}const g="_getImageData"+(o?"Grey":"")+n.pixel_size+"bits",E=su[g](n,h,r,u,_,m,d,f,p);e.getEngine()._uploadDataToTextureDirectly(e,E)}const su={GetTGAHeader:nu,UploadContent:ru,_getImageData8bits:function(e,t,i,n,r,s,a,o,l){const c=i,h=t,d=e.width,u=e.height;let f,_,m,p=0;const g=new Uint8Array(d*u*4);for(m=n;m!==s;m+=r)for(_=a;_!==l;_+=o,p++)f=c[p],g[4*(_+d*m)+3]=255,g[4*(_+d*m)+2]=h[3*f+0],g[4*(_+d*m)+1]=h[3*f+1],g[4*(_+d*m)+0]=h[3*f+2];return g},_getImageData16bits:function(e,t,i,n,r,s,a,o,l){const c=i,h=e.width,d=e.height;let u,f,_,m=0;const p=new Uint8Array(h*d*4);for(_=n;_!==s;_+=r)for(f=a;f!==l;f+=o,m+=2){u=c[m+0]+(c[m+1]<<8);const e=255*((31744&u)>>10)/31|0,t=255*((992&u)>>5)/31|0,i=255*(31&u)/31|0;p[4*(f+h*_)+0]=e,p[4*(f+h*_)+1]=t,p[4*(f+h*_)+2]=i,p[4*(f+h*_)+3]=32768&u?0:255}return p},_getImageData24bits:function(e,t,i,n,r,s,a,o,l){const c=i,h=e.width,d=e.height;let u,f,_=0;const m=new Uint8Array(h*d*4);for(f=n;f!==s;f+=r)for(u=a;u!==l;u+=o,_+=3)m[4*(u+h*f)+3]=255,m[4*(u+h*f)+2]=c[_+0],m[4*(u+h*f)+1]=c[_+1],m[4*(u+h*f)+0]=c[_+2];return m},_getImageData32bits:function(e,t,i,n,r,s,a,o,l){const c=i,h=e.width,d=e.height;let u,f,_=0;const m=new Uint8Array(h*d*4);for(f=n;f!==s;f+=r)for(u=a;u!==l;u+=o,_+=4)m[4*(u+h*f)+2]=c[_+0],m[4*(u+h*f)+1]=c[_+1],m[4*(u+h*f)+0]=c[_+2],m[4*(u+h*f)+3]=c[_+3];return m},_getImageDataGrey8bits:function(e,t,i,n,r,s,a,o,l){const c=i,h=e.width,d=e.height;let u,f,_,m=0;const p=new Uint8Array(h*d*4);for(_=n;_!==s;_+=r)for(f=a;f!==l;f+=o,m++)u=c[m],p[4*(f+h*_)+0]=u,p[4*(f+h*_)+1]=u,p[4*(f+h*_)+2]=u,p[4*(f+h*_)+3]=255;return p},_getImageDataGrey16bits:function(e,t,i,n,r,s,a,o,l){const c=i,h=e.width,d=e.height;let u,f,_=0;const m=new Uint8Array(h*d*4);for(f=n;f!==s;f+=r)for(u=a;u!==l;u+=o,_+=2)m[4*(u+h*f)+0]=c[_+0],m[4*(u+h*f)+1]=c[_+0],m[4*(u+h*f)+2]=c[_+0],m[4*(u+h*f)+3]=c[_+1];return m}};var au=Object.freeze({__proto__:null,_TGATextureLoader:class{constructor(){this.supportCascades=!1}loadCubeData(){throw".env not supported in Cube."}loadData(e,t,i){const n=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),r=nu(n);i(r.width,r.height,t.generateMipMaps,!1,(()=>{ru(t,n)}))}}});const ou="postprocessVertexShader",lu="attribute position: vec2<f32>;uniform scale: vec2<f32>;varying vUV: vec2<f32>;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";Je.ShadersStoreWGSL[ou]=lu;const cu={name:ou,shader:lu};var hu=Object.freeze({__proto__:null,postprocessVertexShaderWGSL:cu});const du="passPixelShader",uu="varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d<f32>;\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,input.vUV);}";Je.ShadersStoreWGSL[du]=uu;const fu={name:du,shader:uu};var _u=Object.freeze({__proto__:null,passPixelShaderWGSL:fu});Je.IncludesShadersStoreWGSL.helperFunctions="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<f32>=vec3<f32> (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<f32>=inMatrix[0];let i1: vec3<f32>=inMatrix[1];let i2: vec3<f32>=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<f32>)->vec3<f32>\n{let nearZeroSection: vec3<f32>=0.0773993808*color;let remainingSection: vec3<f32>=pow(0.947867299*(color+vec3<f32>(0.055)),vec3<f32>(2.4));return mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3<f32>(0.04045)));}\nfn toGammaSpaceExact(color: vec3<f32>)->vec3<f32>\n{let nearZeroSection: vec3<f32>=12.92*color;let remainingSection: vec3<f32>=1.055*pow(color,vec3<f32>(0.41666))-vec3<f32>(0.055);return mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3<f32>(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<f32>)->vec3<f32>\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn toLinearSpaceExact(color);\n#else\nreturn pow(color,vec3<f32>(LinearEncodePowerApprox));\n#endif\n}\nfn toLinearSpaceVec4(color: vec4<f32>)->vec4<f32>\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<f32>)->vec4<f32>\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn vec4<f32>(toGammaSpaceExact(color.rgb),color.a);\n#else\nreturn vec4<f32>(pow(color.rgb,vec3<f32>(GammaEncodePowerApprox)),color.a);\n#endif\n}\nfn toGammaSpaceVec3(color: vec3<f32>)->vec3<f32>\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn toGammaSpaceExact(color);\n#else\nreturn pow(color,vec3<f32>(GammaEncodePowerApprox));\n#endif\n}\nfn squareVec3(value: vec3<f32>)->vec3<f32>\n{return value*value;}\nfn pow5(value: f32)->f32 {let sq: f32=value*value;return sq*sq*value;}\nfn getLuminance(color: vec3<f32>)->f32\n{return clamp(dot(color,LuminanceEncodeApprox),0.,1.);}\nfn getRand(seed: vec2<f32>)->f32 {return fract(sin(dot(seed.xy ,vec2<f32>(12.9898,78.233)))*43758.5453);}\nfn dither(seed: vec2<f32>,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<f32>)->vec4<f32> {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<f32> =color.rgb*D;rgb=toGammaSpaceVec3(rgb);return vec4<f32>(clamp(rgb,vec3<f32>(0.,0.,0.),vec3<f32>(1.,1.,1.)),D); }\nfn fromRGBD(rgbd: vec4<f32>)->vec3<f32> {let rgb=toLinearSpaceVec3(rgbd.rgb);return rgb/rgbd.a;}\nfn parallaxCorrectNormal(vertexPos: vec3<f32>,origVec: vec3<f32>,cubeSize: vec3<f32>,cubePos: vec3<f32>)->vec3<f32> {let invOrigVec: vec3<f32>=vec3<f32>(1.0,1.0,1.0)/origVec;let halfSize: vec3<f32>=cubeSize*0.5;let intersecAtMaxPlane: vec3<f32>=(cubePos+halfSize-vertexPos)*invOrigVec;let intersecAtMinPlane: vec3<f32>=(cubePos-halfSize-vertexPos)*invOrigVec;let largestIntersec: vec3<f32>=max(intersecAtMaxPlane,intersecAtMinPlane);let distance: f32=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);let intersectPositionWS: vec3<f32>=vertexPos+origVec*distance;return intersectPositionWS-cubePos;}\n";const mu="rgbdDecodePixelShader",pu="varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d<f32>;\n#include<helperFunctions>\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=vec4f(fromRGBD(textureSample(textureSampler,textureSamplerSampler,input.vUV)),1.0);}";Je.ShadersStoreWGSL[mu]=pu;const gu={name:mu,shader:pu};var Eu=Object.freeze({__proto__:null,rgbdDecodePixelShaderWGSL:gu});const Tu="rgbdEncodePixelShader",Au="varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d<f32>;\n#include<helperFunctions>\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=toRGBD(textureSample(textureSampler,textureSamplerSampler,input.vUV).rgb);}";Je.ShadersStoreWGSL[Tu]=Au;const vu={name:Tu,shader:Au};var Ru=Object.freeze({__proto__:null,rgbdEncodePixelShaderWGSL:vu});Je.IncludesShadersStore.helperFunctions="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";const Su="rgbdDecodePixelShader",Iu="varying vec2 vUV;uniform sampler2D textureSampler;\n#include<helperFunctions>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{gl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);}";Je.ShadersStore[Su]=Iu;const Cu={name:Su,shader:Iu};var Mu=Object.freeze({__proto__:null,rgbdDecodePixelShader:Cu});const xu="rgbdEncodePixelShader",bu="varying vec2 vUV;uniform sampler2D textureSampler;\n#include<helperFunctions>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{gl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);}";Je.ShadersStore[xu]=bu;const yu={name:xu,shader:bu};var Ou=Object.freeze({__proto__:null,rgbdEncodePixelShader:yu});Je.IncludesShadersStoreWGSL.sceneUboDeclaration="struct Scene {viewProjection : mat4x4<f32>,\n#ifdef MULTIVIEW\nviewProjectionR : mat4x4<f32>,\n#endif \nview : mat4x4<f32>,\nprojection : mat4x4<f32>,\nvEyePosition : vec4<f32>,};var<uniform> scene : Scene;\n";Je.IncludesShadersStoreWGSL.meshUboDeclaration="struct Mesh {world : mat4x4<f32>,\nvisibility : f32,};var<uniform> mesh : Mesh;\n#define WORLD_UBO\n";Je.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<sceneUboDeclaration>\n#include<meshUboDeclaration>\n";Je.IncludesShadersStoreWGSL.uvAttributeDeclaration="#ifdef UV{X}\nattribute uv{X}: vec2f;\n#endif\n";Je.IncludesShadersStoreWGSL.mainUVVaryingDeclaration="#ifdef MAINUV{X}\nvarying vMainUV{X}: vec2f;\n#endif\n";Je.IncludesShadersStoreWGSL.bonesDeclaration="#if NUM_BONE_INFLUENCERS>0\nattribute matricesIndices : vec4<f32>;attribute matricesWeights : vec4<f32>;\n#if NUM_BONE_INFLUENCERS>4\nattribute matricesIndicesExtra : vec4<f32>;attribute matricesWeightsExtra : vec4<f32>;\n#endif\n#ifndef BAKED_VERTEX_ANIMATION_TEXTURE\n#ifdef BONETEXTURE\nvar boneSampler : texture_2d<f32>;uniform boneTextureWidth : f32;\n#else\nuniform mBones : array<mat4x4,BonesPerMesh>;\n#ifdef BONES_VELOCITY_ENABLED\nuniform mPreviousBones : array<mat4x4,BonesPerMesh>;\n#endif\n#endif\n#ifdef BONETEXTURE\nfn readMatrixFromRawSampler(smp : texture_2d<f32>,index : f32)->mat4x4<f32>\n{let offset=i32(index) *4; \nlet m0=textureLoad(smp,vec2<i32>(offset+0,0),0);let m1=textureLoad(smp,vec2<i32>(offset+1,0),0);let m2=textureLoad(smp,vec2<i32>(offset+2,0),0);let m3=textureLoad(smp,vec2<i32>(offset+3,0),0);return mat4x4<f32>(m0,m1,m2,m3);}\n#endif\n#endif\n#endif\n";Je.IncludesShadersStoreWGSL.bakedVertexAnimationDeclaration="#ifdef BAKED_VERTEX_ANIMATION_TEXTURE\nuniform bakedVertexAnimationTime: f32;uniform bakedVertexAnimationTextureSizeInverted: vec2<f32>;uniform bakedVertexAnimationSettings: vec4<f32>;var bakedVertexAnimationTexture : texture_2d<f32>;\n#ifdef INSTANCES\nattribute bakedVertexAnimationSettingsInstanced : vec4<f32>;\n#endif\nfn readMatrixFromRawSamplerVAT(smp : texture_2d<f32>,index : f32,frame : f32)->mat4x4<f32>\n{let offset=i32(index)*4;let frameUV=i32(frame);let m0=textureLoad(smp,vec2<i32>(offset+0,frameUV),0);let m1=textureLoad(smp,vec2<i32>(offset+1,frameUV),0);let m2=textureLoad(smp,vec2<i32>(offset+2,frameUV),0);let m3=textureLoad(smp,vec2<i32>(offset+3,frameUV),0);return mat4x4<f32>(m0,m1,m2,m3);}\n#endif\n";Je.IncludesShadersStoreWGSL.instancesDeclaration="#ifdef INSTANCES\nattribute world0 : vec4<f32>;attribute world1 : vec4<f32>;attribute world2 : vec4<f32>;attribute world3 : vec4<f32>;\n#ifdef INSTANCESCOLOR\nattribute instanceColor : vec4<f32>;\n#endif\n#if defined(THIN_INSTANCES) && !defined(WORLD_UBO)\nuniform world : mat4x4<f32>;\n#endif\n#if defined(VELOCITY) || defined(PREPASS_VELOCITY)\nattribute previousWorld0 : vec4<f32>;attribute previousWorld1 : vec4<f32>;attribute previousWorld2 : vec4<f32>;attribute previousWorld3 : vec4<f32>;\n#ifdef THIN_INSTANCES\nuniform previousWorld : mat4x4<f32>;\n#endif\n#endif\n#else\n#if !defined(WORLD_UBO)\nuniform world : mat4x4<f32>;\n#endif\n#if defined(VELOCITY) || defined(PREPASS_VELOCITY)\nuniform previousWorld : mat4x4<f32>;\n#endif\n#endif\n";Je.IncludesShadersStoreWGSL.prePassVertexDeclaration="#ifdef PREPASS\n#ifdef PREPASS_DEPTH\nvarying vViewPos: vec3f;\n#endif\n#ifdef PREPASS_VELOCITY\nuniform previousViewProjection: mat4x4f;varying vCurrentPosition: vec4f;varying vPreviousPosition: vec4f;\n#endif\n#endif\n";Je.IncludesShadersStoreWGSL.samplerVertexDeclaration="#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0\nvarying v_VARYINGNAME_UV: vec2f;\n#endif\n";Je.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";Je.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";Je.IncludesShadersStoreWGSL.clipPlaneVertexDeclaration="#ifdef CLIPPLANE\nuniform vClipPlane: vec4<f32>;varying fClipDistance: f32;\n#endif\n#ifdef CLIPPLANE2\nuniform vClipPlane2: vec4<f32>;varying fClipDistance2: f32;\n#endif\n#ifdef CLIPPLANE3\nuniform vClipPlane3: vec4<f32>;varying fClipDistance3: f32;\n#endif\n#ifdef CLIPPLANE4\nuniform vClipPlane4: vec4<f32>;varying fClipDistance4: f32;\n#endif\n#ifdef CLIPPLANE5\nuniform vClipPlane5: vec4<f32>;varying fClipDistance5: f32;\n#endif\n#ifdef CLIPPLANE6\nuniform vClipPlane6: vec4<f32>;varying fClipDistance6: f32;\n#endif\n";Je.IncludesShadersStoreWGSL.fogVertexDeclaration="#ifdef FOG\nvarying vFogDistance: vec3f;\n#endif\n";Je.IncludesShadersStoreWGSL.lightVxUboDeclaration="#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<uniform> light{X} : Light{X};\n#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nuniform lightMatrix{X}: array<mat4x4f,SHADOWCSMNUM_CASCADES{X}>;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";Je.IncludesShadersStoreWGSL.morphTargetsVertexGlobalDeclaration="#ifdef MORPHTARGETS\nuniform morphTargetInfluences : array<f32,NUM_MORPH_INFLUENCERS>;\n#ifdef MORPHTARGETS_TEXTURE \nuniform morphTargetTextureIndices : array<f32,NUM_MORPH_INFLUENCERS>;uniform morphTargetTextureInfo : vec3<f32>;var morphTargets : texture_2d_array<f32>;var morphTargetsSampler : sampler;fn readVector3FromRawSampler(targetIndex : i32,vertexIndex : f32)->vec3<f32>\n{ \nlet y=floor(vertexIndex/uniforms.morphTargetTextureInfo.y);let x=vertexIndex-y*uniforms.morphTargetTextureInfo.y;let textureUV=vec2<f32>((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";Je.IncludesShadersStoreWGSL.morphTargetsVertexDeclaration="#ifdef MORPHTARGETS\n#ifndef MORPHTARGETS_TEXTURE\nattribute position{X} : vec3<f32>;\n#ifdef MORPHTARGETS_NORMAL\nattribute normal{X} : vec3<f32>;\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute tangent{X} : vec3<f32>;\n#endif\n#ifdef MORPHTARGETS_UV\nattribute uv_{X} : vec2<f32>;\n#endif\n#elif {X}==0\nuniform morphTargetCount: i32;\n#endif\n#endif\n";Je.IncludesShadersStoreWGSL.logDepthDeclaration="#ifdef LOGARITHMICDEPTH\nuniform logarithmicDepthConstant: f32;varying vFragmentDepth: f32;\n#endif\n";Je.IncludesShadersStoreWGSL.morphTargetsVertexGlobal="#ifdef MORPHTARGETS\n#ifdef MORPHTARGETS_TEXTURE\nvar vertexID : f32;\n#endif\n#endif\n";Je.IncludesShadersStoreWGSL.morphTargetsVertex="#ifdef MORPHTARGETS\n#ifdef MORPHTARGETS_TEXTURE\n#if {X}==0\nfor (var i=0; i<NUM_MORPH_INFLUENCERS; i=i+1) {if (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";Je.IncludesShadersStoreWGSL.instancesVertex="#ifdef INSTANCES\nvar finalWorld=mat4x4<f32>(vertexInputs.world0,vertexInputs.world1,vertexInputs.world2,vertexInputs.world3);\n#if defined(PREPASS_VELOCITY) || defined(VELOCITY)\nvar finalPreviousWorld=mat4x4<f32>(vertexInputs.previousWorld0,vertexInputs.previousWorld1,vertexInputs.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)\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)\nvar finalPreviousWorld=uniforms.previousWorld;\n#endif\n#endif\n";Je.IncludesShadersStoreWGSL.bonesVertex="#ifndef BAKED_VERTEX_ANIMATION_TEXTURE\n#if NUM_BONE_INFLUENCERS>0\nvar influence : mat4x4<f32>;\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";Je.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<f32>;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";Je.IncludesShadersStoreWGSL.prePassVertex="#ifdef PREPASS_DEPTH\nvertexOutputs.vViewPos=(scene.view*worldPos).rgb;\n#endif\n#if defined(PREPASS_VELOCITY) && 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";Je.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";Je.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";Je.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";Je.IncludesShadersStoreWGSL.clipPlaneVertex="#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";Je.IncludesShadersStoreWGSL.fogVertex="#ifdef FOG\nvertexOutputs.vFogDistance=(scene.view*worldPos).xyz;\n#endif\n";Je.IncludesShadersStoreWGSL.shadowsVertex="#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";Je.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";Je.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";const Du="pbrVertexShader",Nu="#include<pbrUboDeclaration>\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<uvAttributeDeclaration>[2..7]\n#include<mainUVVaryingDeclaration>[1..7]\n#ifdef VERTEXCOLOR\nattribute color: vec4f;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n#include<bakedVertexAnimationDeclaration>\n#include<instancesDeclaration>\n#include<prePassVertexDeclaration>\n#include<samplerVertexDeclaration>(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo)\n#include<samplerVertexDeclaration>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail)\n#include<samplerVertexDeclaration>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient)\n#include<samplerVertexDeclaration>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity)\n#include<samplerVertexDeclaration>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive)\n#include<samplerVertexDeclaration>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap)\n#include<samplerVertexDeclaration>(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity)\n#include<samplerVertexDeclaration>(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler)\n#include<samplerVertexDeclaration>(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance)\n#include<samplerVertexDeclaration>(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance)\n#include<samplerVertexDeclaration>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump)\n#include<samplerVertexDeclaration>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal)\n#ifdef CLEARCOAT\n#include<samplerVertexDeclaration>(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat)\n#include<samplerVertexDeclaration>(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness)\n#include<samplerVertexDeclaration>(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump)\n#include<samplerVertexDeclaration>(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint)\n#endif\n#ifdef IRIDESCENCE\n#include<samplerVertexDeclaration>(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence)\n#include<samplerVertexDeclaration>(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness)\n#endif\n#ifdef SHEEN\n#include<samplerVertexDeclaration>(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen)\n#include<samplerVertexDeclaration>(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness)\n#endif\n#ifdef ANISOTROPIC\n#include<samplerVertexDeclaration>(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy)\n#endif\n#ifdef SUBSURFACE\n#include<samplerVertexDeclaration>(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness)\n#include<samplerVertexDeclaration>(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity)\n#include<samplerVertexDeclaration>(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity)\n#include<samplerVertexDeclaration>(_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<harmonicsFunctions>\n#endif\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vColor: vec4f;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<lightVxUboDeclaration>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[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<logDepthDeclaration>\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<morphTargetsVertexGlobal>\n#include<morphTargetsVertex>[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<instancesVertex>\n#if defined(PREPASS) && defined(PREPASS_VELOCITY) && !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<bonesVertex>\n#include<bakedVertexAnimation>\nvar worldPos: vec4f=finalWorld* vec4f(positionUpdated,1.0);vertexOutputs.vPositionW= worldPos.xyz;\n#include<prePassVertex>\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<uvVariableDeclaration>[2..7]\n#include<samplerVertexImplementation>(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_MATRIXNAME_,albedo,_INFONAME_,AlbedoInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_MATRIXNAME_,detail,_INFONAME_,DetailInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_MATRIXNAME_,ambient,_INFONAME_,AmbientInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_MATRIXNAME_,opacity,_INFONAME_,OpacityInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_MATRIXNAME_,emissive,_INFONAME_,EmissiveInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_MATRIXNAME_,lightmap,_INFONAME_,LightmapInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_MATRIXNAME_,reflectivity,_INFONAME_,ReflectivityInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_MATRIXNAME_,microSurfaceSampler,_INFONAME_,MicroSurfaceSamplerInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_MATRIXNAME_,metallicReflectance,_INFONAME_,MetallicReflectanceInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_MATRIXNAME_,reflectance,_INFONAME_,ReflectanceInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_MATRIXNAME_,bump,_INFONAME_,BumpInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_MATRIXNAME_,decal,_INFONAME_,DecalInfos.x)\n#ifdef CLEARCOAT\n#include<samplerVertexImplementation>(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_MATRIXNAME_,clearCoat,_INFONAME_,ClearCoatInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness,_MATRIXNAME_,clearCoatRoughness,_INFONAME_,ClearCoatInfos.z)\n#include<samplerVertexImplementation>(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_MATRIXNAME_,clearCoatBump,_INFONAME_,ClearCoatBumpInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_MATRIXNAME_,clearCoatTint,_INFONAME_,ClearCoatTintInfos.x)\n#endif\n#ifdef IRIDESCENCE\n#include<samplerVertexImplementation>(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence,_MATRIXNAME_,iridescence,_INFONAME_,IridescenceInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness,_MATRIXNAME_,iridescenceThickness,_INFONAME_,IridescenceInfos.z)\n#endif\n#ifdef SHEEN\n#include<samplerVertexImplementation>(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_MATRIXNAME_,sheen,_INFONAME_,SheenInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness,_MATRIXNAME_,sheenRoughness,_INFONAME_,SheenInfos.z)\n#endif\n#ifdef ANISOTROPIC\n#include<samplerVertexImplementation>(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_MATRIXNAME_,anisotropy,_INFONAME_,AnisotropyInfos.x)\n#endif\n#ifdef SUBSURFACE\n#include<samplerVertexImplementation>(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_MATRIXNAME_,thickness,_INFONAME_,ThicknessInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_MATRIXNAME_,refractionIntensity,_INFONAME_,RefractionIntensityInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_MATRIXNAME_,translucencyIntensity,_INFONAME_,TranslucencyIntensityInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,SS_TRANSLUCENCYCOLOR_TEXTURE,_VARYINGNAME_,TranslucencyColor,_MATRIXNAME_,translucencyColor,_INFONAME_,TranslucencyColorInfos.x)\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#include<vertexColorMixing>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}";Je.ShadersStoreWGSL[Du]=Nu;const Pu={name:Du,shader:Nu};var Lu=Object.freeze({__proto__:null,pbrVertexShaderWGSL:Pu});Je.IncludesShadersStoreWGSL.prePassDeclaration="#ifdef PREPASS\n#ifdef PREPASS_DEPTH\nvarying vViewPos: vec3f;\n#endif\n#ifdef PREPASS_VELOCITY\nvarying vCurrentPosition: vec4f;varying vPreviousPosition: vec4f;\n#endif\n#endif\n";Je.IncludesShadersStoreWGSL.oitDeclaration="#ifdef ORDER_INDEPENDENT_TRANSPARENCY\n#define MAX_DEPTH 99999.0\nvar oitDepthSamplerSampler: sampler;var oitDepthSampler: texture_2d<f32>;var oitFrontColorSamplerSampler: sampler;var oitFrontColorSampler: texture_2d<f32>;\n#endif\n";Je.IncludesShadersStoreWGSL.pbrFragmentExtraDeclaration="varying vPositionW: vec3f;\n#if DEBUGMODE>0\nvarying vClipSpacePosition: vec4f;\n#endif\n#include<mainUVVaryingDeclaration>[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";Je.IncludesShadersStoreWGSL.lightUboDeclaration="#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<uniform> light{X} : Light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform textureProjectionMatrix{X}: mat4x4f;var projectionLightTexture{X}Sampler: sampler;var projectionLightTexture{X}: texture_2d<f32>;\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nuniform lightMatrix{X}: array<mat4x4f,SHADOWCSMNUM_CASCADES{X}>;uniform viewFrustumZ{X}: array<f32,SHADOWCSMNUM_CASCADES{X}>;uniform frustumLengths{X}: array<f32,SHADOWCSMNUM_CASCADES{X}>;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<private> vPositionFromLight{X}: array<vec4f,4>;var<private> vDepthMetric{X} : array<f32,4>;\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<f32>;uniform lightSizeUVCorrection{X}: array<vec2f,SHADOWCSMNUM_CASCADES{X}>;uniform depthCorrection{X}: array<f32,SHADOWCSMNUM_CASCADES{X}>;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<f32>;\n#endif\n#ifdef SHADOWCSMDEBUG{X}\nconst vCascadeColorsMultiplier{X}: array<vec3f,8>=array<vec3f,8>\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<f32>;\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<f32>;\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<f32>;\n#endif\nuniform lightMatrix{X}: mat4x4f;\n#endif\n#endif\n#endif\n";Je.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<f32>;\n#endif\n";Je.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";Je.IncludesShadersStoreWGSL.pbrFragmentSamplersDeclaration="#include<samplerFragmentDeclaration>(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_SAMPLERNAME_,albedo)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_SAMPLERNAME_,reflectivity)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_SAMPLERNAME_,microSurface)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_SAMPLERNAME_,metallicReflectance)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_SAMPLERNAME_,reflectance)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_SAMPLERNAME_,decal)\n#ifdef CLEARCOAT\n#include<samplerFragmentDeclaration>(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_SAMPLERNAME_,clearCoat)\n#include<samplerFragmentAlternateDeclaration>(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness)\n#if defined(CLEARCOAT_TEXTURE_ROUGHNESS)\nvar clearCoatRoughnessSamplerSampler: sampler;var clearCoatRoughnessSampler: texture_2d<f32>;\n#endif\n#include<samplerFragmentDeclaration>(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_SAMPLERNAME_,clearCoatBump)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_SAMPLERNAME_,clearCoatTint)\n#endif\n#ifdef IRIDESCENCE\n#include<samplerFragmentDeclaration>(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence,_SAMPLERNAME_,iridescence)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness,_SAMPLERNAME_,iridescenceThickness)\n#endif\n#ifdef SHEEN\n#include<samplerFragmentDeclaration>(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_SAMPLERNAME_,sheen)\n#include<samplerFragmentAlternateDeclaration>(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness)\n#if defined(SHEEN_ROUGHNESS) && defined(SHEEN_TEXTURE_ROUGHNESS)\nvar sheenRoughnessSamplerSampler: sampler;var sheenRoughnessSampler: texture_2d<f32>;\n#endif\n#endif\n#ifdef ANISOTROPIC\n#include<samplerFragmentDeclaration>(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_SAMPLERNAME_,anisotropy)\n#endif\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nvar reflectionSamplerSampler: sampler;var reflectionSampler: texture_cube<f32>;\n#ifdef LODBASEDMICROSFURACE\n#else\nvar reflectionLowSamplerSampler: sampler;var reflectionLowSampler: texture_cube<f32>;var reflectionHighSamplerSampler: sampler;var reflectionHighSampler: texture_cube<f32>;\n#endif\n#ifdef USEIRRADIANCEMAP\nvar irradianceSamplerSampler: sampler;var irradianceSampler: texture_cube<f32>;\n#endif\n#else\nvar reflectionSamplerSampler: sampler;var reflectionSampler: texture_2d<f32>;\n#ifdef LODBASEDMICROSFURACE\n#else\nvar reflectionLowSamplerSampler: sampler;var reflectionLowSampler: texture_2d<f32>;var reflectionHighSamplerSampler: sampler;var reflectionHighSampler: texture_2d<f32>;\n#endif\n#ifdef USEIRRADIANCEMAP\nvar irradianceSamplerSampler: sampler;var irradianceSampler: texture_2d<f32>;\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<f32>;\n#endif\n#ifdef SUBSURFACE\n#ifdef SS_REFRACTION\n#ifdef SS_REFRACTIONMAP_3D\nvar refractionSamplerSampler: sampler;var refractionSampler: texture_cube<f32>;\n#ifdef LODBASEDMICROSFURACE\n#else\nvar refractionLowSamplerSampler: sampler;var refractionLowSampler: texture_cube<f32>;var refractionHighSamplerSampler: sampler;var refractionHighSampler: texture_cube<f32>;\n#endif\n#else\nvar refractionSamplerSampler: sampler;var refractionSampler: texture_2d<f32>;\n#ifdef LODBASEDMICROSFURACE\n#else\nvar refractionLowSamplerSampler: sampler;var refractionLowSampler: texture_2d<f32>;var refractionHighSamplerSampler: sampler;var refractionHighSampler: texture_2d<f32>;\n#endif\n#endif\n#endif\n#include<samplerFragmentDeclaration>(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_SAMPLERNAME_,thickness)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_SAMPLERNAME_,refractionIntensity)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_SAMPLERNAME_,translucencyIntensity)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,SS_TRANSLUCENCYCOLOR_TEXTURE,_VARYINGNAME_,TranslucencyColor,_SAMPLERNAME_,translucencyColor)\n#endif\n";Je.IncludesShadersStoreWGSL.imageProcessingDeclaration="#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<f32>;\n#else\nvar txColorTransformSampler: sampler;var txColorTransform: texture_2d<f32>;\n#endif\nuniform colorTransformSettings: vec4f;\n#endif\n#ifdef DITHER\nuniform ditherIntensity: f32;\n#endif\n";Je.IncludesShadersStoreWGSL.clipPlaneFragmentDeclaration="#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";Je.IncludesShadersStoreWGSL.fogFragmentDeclaration="#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";Je.IncludesShadersStoreWGSL.subSurfaceScatteringFunctions="fn testLightingForSSS(diffusionProfile: f32)->bool\n{return diffusionProfile<1.;}";Je.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);}";Je.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";Je.IncludesShadersStoreWGSL.imageProcessingFunctions="#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 (peak<PBRNeutralStartCompression) {return result;}\nvar d: f32=1.-PBRNeutralStartCompression;var newPeak: f32=1.-d*d/(peak+d-PBRNeutralStartCompression);result*=newPeak/peak;var g: f32=1.-1./(PBRNeutralDesaturation*(peak-newPeak)+1.);return mix(result,newPeak* vec3f(1,1,1),g);}\n#endif\n#if TONEMAPPING==2\nconst ACESInputMat: mat3x3f= mat3x3f(\nvec3f(0.59719,0.07600,0.02840),\nvec3f(0.35458,0.90834,0.13383),\nvec3f(0.04823,0.01566,0.83777)\n);const ACESOutputMat: mat3x3f= mat3x3f(\nvec3f( 1.60475,-0.10208,-0.00327),\nvec3f(-0.53108, 1.10813,-0.07276),\nvec3f(-0.07367,-0.00605, 1.07602)\n);fn RRTAndODTFit(v: vec3f)->vec3f\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);}";Je.IncludesShadersStoreWGSL.shadowsFragmentFunctions="#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<f32>,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<f32>,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<vec3f,4>;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))<depth) {visibility-=0.25;};if (unpack(textureSample(shadowTexture,shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) {visibility-=0.25;};if (unpack(textureSample(shadowTexture,shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) {visibility-=0.25;};if (unpack(textureSample(shadowTexture,shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) {visibility-=0.25;};\n#else\nif (textureSample(shadowTexture,shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) {visibility-=0.25;};if (textureSample(shadowTexture,shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) {visibility-=0.25;};if (textureSample(shadowTexture,shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) {visibility-=0.25;};if (textureSample(shadowTexture,shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) {visibility-=0.25;};\n#endif\nreturn min(1.0,visibility+darkness);}\nfn computeShadowWithESMCube(worldPos: vec3f,lightPosition: vec3f,shadowTexture: texture_cube<f32>,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<f32>,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<f32>,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<f32>,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<f32>,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<vec2f,4>;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.))<shadowPixelDepth) {visibility-=0.25;}\nif (unpack(textureSampleLevel(shadowTexture,shadowSampler,uv+poissonDisk[1]*mapSize,0.))<shadowPixelDepth) {visibility-=0.25;}\nif (unpack(textureSampleLevel(shadowTexture,shadowSampler,uv+poissonDisk[2]*mapSize,0.))<shadowPixelDepth) {visibility-=0.25;}\nif (unpack(textureSampleLevel(shadowTexture,shadowSampler,uv+poissonDisk[3]*mapSize,0.))<shadowPixelDepth) {visibility-=0.25;}\n#else\nif (textureSampleLevel(shadowTexture,shadowSampler,uv+poissonDisk[0]*mapSize,0.).x<shadowPixelDepth) {visibility-=0.25;}\nif (textureSampleLevel(shadowTexture,shadowSampler,uv+poissonDisk[1]*mapSize,0.).x<shadowPixelDepth) {visibility-=0.25;}\nif (textureSampleLevel(shadowTexture,shadowSampler,uv+poissonDisk[2]*mapSize,0.).x<shadowPixelDepth) {visibility-=0.25;}\nif (textureSampleLevel(shadowTexture,shadowSampler,uv+poissonDisk[3]*mapSize,0.).x<shadowPixelDepth) {visibility-=0.25;}\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);}}\nfn computeShadowWithESM(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_2d<f32>,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<f32>,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<vec3f,64>=array<vec3f,64> (\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<vec3f,64>=array<vec3f,64> (\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<f32>,depthSampler: sampler,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32,searchTapCount: i32,pcfTapCount: i32,poissonSamplers: array<vec3f,64>,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<searchTapCount; i ++) {blockerDepth=textureSample(depthTexture,depthSampler, uvDepth.xy+(lightSizeUV*lightSizeUVCorrection*shadowMapSizeInverse*PoissonSamplers32[i].xy),layer).r;numBlocker+=select(0.,1.,blockerDepth<depthMetric);sumBlockerDepth+=select(0.,blockerDepth,blockerDepth<depthMetric);}\nvar avgBlockerDepth: f32=sumBlockerDepth/numBlocker;var AAOffset: f32=shadowMapSizeInverse*10.;var penumbraRatio: f32=((depthMetric-avgBlockerDepth)*depthCorrection+AAOffset);var filterRadius: vec4f= vec4f(penumbraRatio*lightSizeUV*lightSizeUVCorrection*shadowMapSizeInverse,0.,0.);var random: f32=getRand(vPositionFromLight.xy);var rotationAngle: f32=random*3.1415926;var rotationVector: vec2f= vec2f(cos(rotationAngle),sin(rotationAngle));var shadow: f32=0.;for (var i: i32=0; i<pcfTapCount; i++) {var offset: vec4f= vec4f(poissonSamplers[i],0.);offset= vec4f(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.,0.);let coords=uvDepthLayer+offset*filterRadius;shadow+=textureSampleCompare(shadowTexture,shadowSampler,coords.xy,i32(coords.z),coords.w);}\nshadow/= f32(pcfTapCount);shadow=mix(shadow,1.,min((depthMetric-avgBlockerDepth)*depthCorrection*penumbraDarkness,1.));shadow=mix(darkness,1.,shadow);return select(computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff),1.0,numBlocker<1.0);}\nfn computeShadowWithPCSS(vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d<f32>,depthSampler: sampler,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32,searchTapCount: i32,pcfTapCount: i32,poissonSamplers: array<vec3f,64>)->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<searchTapCount; i ++) {if (exitCondition) {break;}\nblockerDepth=textureSampleLevel(depthTexture,depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy),0).r;numBlocker+=select(0.,1.,blockerDepth<depthMetric);sumBlockerDepth+=select(0.,blockerDepth,blockerDepth<depthMetric);}\nexitCondition=exitCondition || numBlocker<1.0;var avgBlockerDepth: f32=sumBlockerDepth/numBlocker;var AAOffset: f32=shadowMapSizeInverse*10.;var penumbraRatio: f32=((depthMetric-avgBlockerDepth)+AAOffset);var filterRadius: f32=penumbraRatio*lightSizeUV*shadowMapSizeInverse;var random: f32=getRand(vPositionFromLight.xy);var rotationAngle: f32=random*3.1415926;var rotationVector: vec2f= vec2f(cos(rotationAngle),sin(rotationAngle));var shadow: f32=0.;for (var i: i32=0; i<pcfTapCount; i++) {if (exitCondition) {break;}\nvar offset: vec3f=poissonSamplers[i];offset= vec3f(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);let coords=uvDepth+offset*filterRadius;shadow+=textureSampleCompareLevel(shadowTexture,shadowSampler,coords.xy,coords.z);}\nshadow/= f32(pcfTapCount);shadow=mix(shadow,1.,depthMetric-avgBlockerDepth);shadow=mix(darkness,1.,shadow);return select(computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff),1.0,exitCondition);}\nfn computeShadowWithPCSS16(vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d<f32>,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<f32>,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<f32>,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<f32>,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<f32>,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<f32>,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";Je.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;}";Je.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}";Je.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 (iridescenceIOR<outsideIOR) {phi12=PI;}\nvar phi21: f32=PI-phi12;var baseIOR: vec3f=getIORTfromAirToSurfaceR0(clamp(baseF0,vec3f(0.0),vec3f(0.9999))); \nvar R1: vec3f=getR0fromIORsVec3(baseIOR,iridescenceIOR);var R23: vec3f=fresnelSchlickGGXVec3(cosTheta2,R1, vec3f(1.));var phi23: vec3f= vec3f(0.0);if (baseIOR[0]<iridescenceIOR) {phi23[0]=PI;}\nif (baseIOR[1]<iridescenceIOR) {phi23[1]=PI;}\nif (baseIOR[2]<iridescenceIOR) {phi23[2]=PI;}\nvar opd: f32=2.0*iridescenceIOR*thinFilmThickness*cosTheta2;var phi: vec3f= vec3f(phi21)+phi23;var R123: vec3f=clamp(R12*R23,vec3f(1e-5),vec3f(0.9999));var r123: vec3f=sqrt(R123);var Rs: vec3f=(T121*T121)*R23/( vec3f(1.0)-R123);var C0: vec3f=R12+Rs;I=C0;var Cm: vec3f=Rs-T121;for (var m: i32=1; m<=2; m++)\n{Cm*=r123;var Sm: vec3f=2.0*evalSensitivity( f32(m)*opd, f32(m)*phi);I+=Cm*Sm;}\nreturn max(I, vec3f(0.0));}\n#endif\nfn normalDistributionFunction_TrowbridgeReitzGGX(NdotH: f32,alphaG: f32)->f32\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";Je.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<f32>,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; i<NUM_SAMPLES; i++)\n{var Xi: vec2f=hammersley(i,NUM_SAMPLES);var Ls: vec3f=hemisphereCosSample(Xi);Ls=normalize(Ls);var Ns: vec3f= vec3f(0.,0.,1.);var NoL: f32=dot(Ns,Ls);if (NoL>0.) {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<f32>,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; i<NUM_SAMPLES; i++)\n{var Xi: vec2f=hammersley(i,NUM_SAMPLES);var H: vec3f=hemisphereImportanceSampleDggx(Xi,alphaG);var NoV: f32=1.;var NoH: f32=H.z;var NoH2: f32=H.z*H.z;var NoL: f32=2.*NoH2-1.;var L: vec3f= vec3f(2.*NoH*H.x,2.*NoH*H.y,NoL);L=normalize(L);if (NoL>0.) {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";Je.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<f32>,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";Je.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";Je.IncludesShadersStoreWGSL.bumpFragmentMainFunctions="#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<f32>(\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<f32>(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";Je.IncludesShadersStoreWGSL.bumpFragmentFunctions="#if defined(BUMP)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_SAMPLERNAME_,bump)\n#endif\n#if defined(DETAIL)\n#include<samplerFragmentDeclaration>(_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; i<iMaxSamples; i++)\n{currSampledHeight=textureSample(bumpSampler,bumpSamplerSampler,texCoord+vCurrOffset).w;if (!keepWorking)\n{}\nelse if (currSampledHeight>currRayHeight)\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";Je.IncludesShadersStoreWGSL.reflectionFunction="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";Je.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";Je.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<decalFragment>\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<decalFragment>\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<ALPHATESTVALUE) {discard;}\n#endif\n#ifndef ALPHABLEND\nalpha=1.0;\n#endif\n#endif\n#endif\noutParams.surfaceAlbedo=surfaceAlbedo;outParams.alpha=alpha;return outParams;}\n";Je.IncludesShadersStoreWGSL.pbrBlockReflectivity="struct reflectivityOutParams\n{microSurface: f32,\nroughness: f32,\nsurfaceReflectivityColor: vec3f,\n#ifdef METALLICWORKFLOW\nsurfaceAlbedo: vec3f,\n#endif\n#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)\nambientOcclusionColor: vec3f,\n#endif\n#if DEBUGMODE>0\n#ifdef METALLICWORKFLOW\nmetallicRoughness: vec2f,\n#ifdef REFLECTIVITY\nsurfaceMetallicColorMap: vec4f,\n#endif\n#ifndef FROSTBITE_REFLECTANCE\nmetallicF0: vec3f,\n#endif\n#else\n#ifdef REFLECTIVITY\nsurfaceReflectivityColorMap: vec4f,\n#endif\n#endif\n#endif\n};\n#define pbr_inline\nfn reflectivityBlock(\nvReflectivityColor: vec4f\n#ifdef METALLICWORKFLOW\n,surfaceAlbedo: vec3f\n,metallicReflectanceFactors: vec4f\n#endif\n#ifdef REFLECTIVITY\n,reflectivityInfos: vec3f\n,surfaceMetallicOrReflectivityColorMap: vec4f\n#endif\n#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)\n,ambientOcclusionColorIn: vec3f\n#endif\n#ifdef MICROSURFACEMAP\n,microSurfaceTexel: vec4f\n#endif\n#ifdef DETAIL\n,detailColor: vec4f\n,vDetailInfos: vec4f\n#endif\n)->reflectivityOutParams\n{var outParams: reflectivityOutParams;var microSurface: f32=vReflectivityColor.a;var surfaceReflectivityColor: vec3f=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvar metallicRoughness: vec2f=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\n#if DEBUGMODE>0\noutParams.surfaceMetallicColorMap=surfaceMetallicOrReflectivityColorMap;\n#endif\n#ifdef AOSTOREINMETALMAPRED\nvar aoStoreInMetalMap: vec3f= vec3f(surfaceMetallicOrReflectivityColorMap.r,surfaceMetallicOrReflectivityColorMap.r,surfaceMetallicOrReflectivityColorMap.r);outParams.ambientOcclusionColor=mix(ambientOcclusionColorIn,aoStoreInMetalMap,reflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicOrReflectivityColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicOrReflectivityColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicOrReflectivityColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicOrReflectivityColorMap.g;\n#endif\n#endif\n#endif\n#ifdef DETAIL\nvar detailRoughness: f32=mix(0.5,detailColor.b,vDetailInfos.w);var loLerp: f32=mix(0.,metallicRoughness.g,detailRoughness*2.);var hiLerp: f32=mix(metallicRoughness.g,1.,(detailRoughness-0.5)*2.);metallicRoughness.g=mix(loLerp,hiLerp,step(detailRoughness,0.5));\n#endif\n#ifdef MICROSURFACEMAP\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n#if DEBUGMODE>0\noutParams.metallicRoughness=metallicRoughness;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_METALLICROUGHNESS\nmicroSurface=1.0-metallicRoughness.g;var baseColor: vec3f=surfaceAlbedo;\n#ifdef FROSTBITE_REFLECTANCE\noutParams.surfaceAlbedo=baseColor.rgb*(1.0-metallicRoughness.r);surfaceReflectivityColor=mix(0.16*reflectance*reflectance,baseColor,metallicRoughness.r);\n#else\nvar metallicF0: vec3f=metallicReflectanceFactors.rgb;\n#if DEBUGMODE>0\noutParams.metallicF0=metallicF0;\n#endif\noutParams.surfaceAlbedo=mix(baseColor.rgb*(1.0-metallicF0), vec3f(0.,0.,0.),metallicRoughness.r);surfaceReflectivityColor=mix(metallicF0,baseColor,metallicRoughness.r);\n#endif\n#else\n#ifdef REFLECTIVITY\nsurfaceReflectivityColor*=surfaceMetallicOrReflectivityColorMap.rgb;\n#if DEBUGMODE>0\noutParams.surfaceReflectivityColorMap=surfaceMetallicOrReflectivityColorMap;\n#endif\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceMetallicOrReflectivityColorMap.a;microSurface*=reflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_MICROSURFACE\n#endif\n#endif\n#endif\nmicroSurface=saturate(microSurface);var roughness: f32=1.-microSurface;outParams.microSurface=microSurface;outParams.roughness=roughness;outParams.surfaceReflectivityColor=surfaceReflectivityColor;return outParams;}\n";Je.IncludesShadersStoreWGSL.pbrBlockAmbientOcclusion="struct ambientOcclusionOutParams\n{ambientOcclusionColor: vec3f,\n#if DEBUGMODE>0 && defined(AMBIENT)\nambientOcclusionColorMap: vec3f\n#endif\n};\n#define pbr_inline\nfn ambientOcclusionBlock(\n#ifdef AMBIENT\nambientOcclusionColorMap_: vec3f,\nvAmbientInfos: vec4f\n#endif\n)->ambientOcclusionOutParams\n{ \nvar outParams: ambientOcclusionOutParams;var ambientOcclusionColor: vec3f= vec3f(1.,1.,1.);\n#ifdef AMBIENT\nvar ambientOcclusionColorMap: vec3f=ambientOcclusionColorMap_*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap= vec3f(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#if DEBUGMODE>0\noutParams.ambientOcclusionColorMap=ambientOcclusionColorMap;\n#endif\n#endif\noutParams.ambientOcclusionColor=ambientOcclusionColor;return outParams;}\n";Je.IncludesShadersStoreWGSL.pbrBlockAlphaFresnel="#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\nstruct alphaFresnelOutParams\n{alpha: f32};fn faceforward(N: vec3<f32>,I: vec3<f32>,Nref: vec3<f32>)->vec3<f32> {return select(N,-N,dot(Nref,I)>0.0);}\n#define pbr_inline\nfn alphaFresnelBlock(\nnormalW: vec3f,\nviewDirectionW: vec3f,\nalpha: f32,\nmicroSurface: f32\n)->alphaFresnelOutParams\n{var outParams: alphaFresnelOutParams;var opacityPerceptual: f32=alpha;\n#ifdef LINEARALPHAFRESNEL\nvar opacity0: f32=opacityPerceptual;\n#else\nvar opacity0: f32=opacityPerceptual*opacityPerceptual;\n#endif\nvar opacity90: f32=fresnelGrazingReflectance(opacity0);var normalForward: vec3f=faceforward(normalW,-viewDirectionW,normalW);outParams.alpha=getReflectanceFromAnalyticalBRDFLookup_Jones(saturate(dot(viewDirectionW,normalForward)), vec3f(opacity0), vec3f(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (outParams.alpha<ALPHATESTVALUE) {discard;}\n#ifndef ALPHABLEND\noutParams.alpha=1.0;\n#endif\n#endif\nreturn outParams;}\n#endif\n#endif\n";Je.IncludesShadersStoreWGSL.pbrBlockAnisotropic="#ifdef ANISOTROPIC\nstruct anisotropicOutParams\n{anisotropy: f32,\nanisotropicTangent: vec3f,\nanisotropicBitangent: vec3f,\nanisotropicNormal: vec3f,\n#if DEBUGMODE>0 && defined(ANISOTROPIC_TEXTURE)\nanisotropyMapData: vec3f\n#endif\n};\n#define pbr_inline\nfn anisotropicBlock(\nvAnisotropy: vec3f,\nroughness: f32,\n#ifdef ANISOTROPIC_TEXTURE\nanisotropyMapData: vec3f,\n#endif\nTBN: mat3x3f,\nnormalW: vec3f,\nviewDirectionW: vec3f\n)->anisotropicOutParams\n{ \nvar outParams: anisotropicOutParams;var anisotropy: f32=vAnisotropy.b;var anisotropyDirection: vec3f= vec3f(vAnisotropy.xy,0.);\n#ifdef ANISOTROPIC_TEXTURE\nvar amd=anisotropyMapData.rg;anisotropy*=anisotropyMapData.b;\n#if DEBUGMODE>0\noutParams.anisotropyMapData=anisotropyMapData;\n#endif\namd=amd*2.0-1.0;\n#ifdef ANISOTROPIC_LEGACY\nanisotropyDirection=vec3f(anisotropyDirection.xy*amd,anisotropyDirection.z);\n#else\nanisotropyDirection=vec3f(mat2x2f(anisotropyDirection.x,anisotropyDirection.y,-anisotropyDirection.y,anisotropyDirection.x)*normalize(amd),anisotropyDirection.z);\n#endif\n#endif\nvar anisoTBN: mat3x3f= mat3x3f(normalize(TBN[0]),normalize(TBN[1]),normalize(TBN[2]));var anisotropicTangent: vec3f=normalize(anisoTBN*anisotropyDirection);var anisotropicBitangent: vec3f=normalize(cross(anisoTBN[2],anisotropicTangent));outParams.anisotropy=anisotropy;outParams.anisotropicTangent=anisotropicTangent;outParams.anisotropicBitangent=anisotropicBitangent;outParams.anisotropicNormal=getAnisotropicBentNormals(anisotropicTangent,anisotropicBitangent,normalW,viewDirectionW,anisotropy,roughness);return outParams;}\n#endif\n";Je.IncludesShadersStoreWGSL.pbrBlockReflection="#ifdef REFLECTION\nstruct reflectionOutParams\n{environmentRadiance: vec4f\n,environmentIrradiance: vec3f\n#ifdef REFLECTIONMAP_3D\n,reflectionCoords: vec3f\n#else\n,reflectionCoords: vec2f\n#endif\n#ifdef SS_TRANSLUCENCY\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)\n,irradianceVector: vec3f\n#endif\n#endif\n#endif\n};\n#define pbr_inline\n#ifdef REFLECTIONMAP_3D\nfn createReflectionCoords(\nvPositionW: vec3f,\nnormalW: vec3f,\n#ifdef ANISOTROPIC\nanisotropicOut: anisotropicOutParams,\n#endif\n)->vec3f\n{var reflectionCoords: vec3f;\n#else\nfn createReflectionCoords(\nvPositionW: vec3f,\nnormalW: vec3f,\n#ifdef ANISOTROPIC\nanisotropicOut: anisotropicOutParams,\n#endif\n)->vec2f\n{ \nvar reflectionCoords: vec2f;\n#endif\n#ifdef ANISOTROPIC\nvar reflectionVector: vec3f=computeReflectionCoords( vec4f(vPositionW,1.0),anisotropicOut.anisotropicNormal);\n#else\nvar reflectionVector: vec3f=computeReflectionCoords( vec4f(vPositionW,1.0),normalW);\n#endif\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n#ifdef REFLECTIONMAP_3D\nreflectionCoords=reflectionVector;\n#else\nreflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\nreturn reflectionCoords;}\n#define pbr_inline\nfn sampleReflectionTexture(\nalphaG: f32\n,vReflectionMicrosurfaceInfos: vec3f\n,vReflectionInfos: vec2f\n,vReflectionColor: vec3f\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\n,NdotVUnclamped: f32\n#endif\n#ifdef LINEARSPECULARREFLECTION\n,roughness: f32\n#endif\n#ifdef REFLECTIONMAP_3D\n,reflectionSampler: texture_cube<f32>\n,reflectionSamplerSampler: sampler\n,reflectionCoords: vec3f\n#else\n,reflectionSampler: texture_2d<f32>\n,reflectionSamplerSampler: sampler\n,reflectionCoords: vec2f\n#endif\n#ifndef LODBASEDMICROSFURACE\n#ifdef REFLECTIONMAP_3D\n,reflectionLowSampler: texture_cube<f32>\n,reflectionLowSamplerSampler: sampler\n,reflectionHighSampler: texture_cube<f32>\n,reflectionHighSamplerSampler: sampler\n#else\n,reflectionLowSampler: texture_2d<f32>\n,reflectionLowSamplerSampler: sampler\n,reflectionHighSampler: texture_2d<f32>\n,reflectionHighSamplerSampler: sampler\n#endif\n#endif\n#ifdef REALTIME_FILTERING\n,vReflectionFilteringInfo: vec2f\n#endif \n)->vec4f\n{var environmentRadiance: vec4f;\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nvar reflectionLOD: f32=getLodFromAlphaGNdotV(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#elif defined(LINEARSPECULARREFLECTION)\nvar reflectionLOD: f32=getLinearLodFromRoughness(vReflectionMicrosurfaceInfos.x,roughness);\n#else\nvar reflectionLOD: f32=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG);\n#endif\n#ifdef LODBASEDMICROSFURACE\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\nvar automaticReflectionLOD: f32=UNPACK_LOD(textureSample(reflectionSampler,reflectionSamplerSampler,reflectionCoords).a);var requestedReflectionLOD: f32=max(automaticReflectionLOD,reflectionLOD);\n#else\nvar requestedReflectionLOD: f32=reflectionLOD;\n#endif\n#ifdef REALTIME_FILTERING\nenvironmentRadiance= vec4f(radiance(alphaG,reflectionSampler,reflectionSamplerSampler,reflectionCoords,vReflectionFilteringInfo),1.0);\n#else\nenvironmentRadiance=textureSampleLevel(reflectionSampler,reflectionSamplerSampler,reflectionCoords,reflectionLOD);\n#endif\n#else\nvar lodReflectionNormalized: f32=saturate(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x));var lodReflectionNormalizedDoubled: f32=lodReflectionNormalized*2.0;var environmentMid: vec4f=textureSample(reflectionSampler,reflectionSamplerSampler,reflectionCoords);if (lodReflectionNormalizedDoubled<1.0){environmentRadiance=mix(\ntextureSample(reflectionHighSampler,reflectionHighSamplerSampler,reflectionCoords),\nenvironmentMid,\nlodReflectionNormalizedDoubled\n);} else {environmentRadiance=mix(\nenvironmentMid,\ntextureSample(reflectionLowSampler,reflectionLowSamplerSampler,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);}\n#endif\nvar envRadiance=environmentRadiance.rgb;\n#ifdef RGBDREFLECTION\nenvRadiance=fromRGBD(environmentRadiance);\n#endif\n#ifdef GAMMAREFLECTION\nenvRadiance=toLinearSpaceVec3(environmentRadiance.rgb);\n#endif\nenvRadiance*=vReflectionInfos.x;envRadiance*=vReflectionColor.rgb;return vec4f(envRadiance,environmentRadiance.a);}\n#define pbr_inline\nfn reflectionBlock(\nvPositionW: vec3f\n,normalW: vec3f\n,alphaG: f32\n,vReflectionMicrosurfaceInfos: vec3f\n,vReflectionInfos: vec2f\n,vReflectionColor: vec3f\n#ifdef ANISOTROPIC\n,anisotropicOut: anisotropicOutParams\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\n,NdotVUnclamped: f32\n#endif\n#ifdef LINEARSPECULARREFLECTION\n,roughness: f32\n#endif\n#ifdef REFLECTIONMAP_3D\n,reflectionSampler: texture_cube<f32>\n,reflectionSamplerSampler: sampler\n#else\n,reflectionSampler: texture_2d<f32>\n,reflectionSamplerSampler: sampler\n#endif\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\n,vEnvironmentIrradiance: vec3f\n#endif\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)\n,reflectionMatrix: mat4x4f\n#endif\n#endif\n#ifdef USEIRRADIANCEMAP\n#ifdef REFLECTIONMAP_3D\n,irradianceSampler: texture_cube<f32>\n,irradianceSamplerSampler: sampler \n#else\n,irradianceSampler: texture_2d<f32>\n,irradianceSamplerSampler: sampler \n#endif\n#endif\n#ifndef LODBASEDMICROSFURACE\n#ifdef REFLECTIONMAP_3D\n,reflectionLowSampler: texture_cube<f32>\n,reflectionLowSamplerSampler: sampler \n,reflectionHighSampler: texture_cube<f32>\n,reflectionHighSamplerSampler: sampler \n#else\n,reflectionLowSampler: texture_2d<f32>\n,reflectionLowSamplerSampler: sampler \n,reflectionHighSampler: texture_2d<f32>\n,reflectionHighSamplerSampler: sampler \n#endif\n#endif\n#ifdef REALTIME_FILTERING\n,vReflectionFilteringInfo: vec2f\n#endif\n)->reflectionOutParams\n{var outParams: reflectionOutParams;var environmentRadiance: vec4f= vec4f(0.,0.,0.,0.);\n#ifdef REFLECTIONMAP_3D\nvar reflectionCoords: vec3f= vec3f(0.);\n#else\nvar reflectionCoords: vec2f= vec2f(0.);\n#endif\nreflectionCoords=createReflectionCoords(\nvPositionW,\nnormalW,\n#ifdef ANISOTROPIC\nanisotropicOut,\n#endif \n);environmentRadiance=sampleReflectionTexture(\nalphaG\n,vReflectionMicrosurfaceInfos\n,vReflectionInfos\n,vReflectionColor\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\n,NdotVUnclamped\n#endif\n#ifdef LINEARSPECULARREFLECTION\n,roughness\n#endif\n#ifdef REFLECTIONMAP_3D\n,reflectionSampler\n,reflectionSamplerSampler\n,reflectionCoords\n#else\n,reflectionSampler\n,reflectionSamplerSampler\n,reflectionCoords\n#endif\n#ifndef LODBASEDMICROSFURACE\n,reflectionLowSampler\n,reflectionLowSamplerSampler\n,reflectionHighSampler\n,reflectionHighSamplerSampler\n#endif\n#ifdef REALTIME_FILTERING\n,vReflectionFilteringInfo\n#endif \n);var environmentIrradiance: vec3f= vec3f(0.,0.,0.);\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\n#ifdef ANISOTROPIC\nvar irradianceVector: vec3f= (reflectionMatrix* vec4f(anisotropicOut.anisotropicNormal,0)).xyz;\n#else\nvar irradianceVector: vec3f= (reflectionMatrix* vec4f(normalW,0)).xyz;\n#endif\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\n#ifdef INVERTCUBICMAP\nirradianceVector.y*=-1.0;\n#endif\n#if defined(REALTIME_FILTERING)\nenvironmentIrradiance=irradiance(reflectionSampler,reflectionSamplerSampler,irradianceVector,vReflectionFilteringInfo);\n#else\nenvironmentIrradiance=computeEnvironmentIrradiance(irradianceVector);\n#endif\n#ifdef SS_TRANSLUCENCY\noutParams.irradianceVector=irradianceVector;\n#endif\n#endif\n#elif defined(USEIRRADIANCEMAP)\nvar environmentIrradiance4: vec4f=textureSample(irradianceSampler,irradianceSamplerSampler,reflectionCoords);environmentIrradiance=environmentIrradiance4.rgb;\n#ifdef RGBDREFLECTION\nenvironmentIrradiance=fromRGBD(environmentIrradiance4);\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentIrradiance=toLinearSpaceVec3(environmentIrradiance.rgb);\n#endif\n#endif\nenvironmentIrradiance*=vReflectionColor.rgb;outParams.environmentRadiance=environmentRadiance;outParams.environmentIrradiance=environmentIrradiance;outParams.reflectionCoords=reflectionCoords;return outParams;}\n#endif\n";Je.IncludesShadersStoreWGSL.pbrBlockSheen="#ifdef SHEEN\nstruct sheenOutParams\n{sheenIntensity: f32\n,sheenColor: vec3f\n,sheenRoughness: f32\n#ifdef SHEEN_LINKWITHALBEDO\n,surfaceAlbedo: vec3f\n#endif\n#if defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING)\n,sheenAlbedoScaling: f32\n#endif\n#if defined(REFLECTION) && defined(ENVIRONMENTBRDF)\n,finalSheenRadianceScaled: vec3f\n#endif\n#if DEBUGMODE>0\n#ifdef SHEEN_TEXTURE\n,sheenMapData: vec4f\n#endif\n#if defined(REFLECTION) && defined(ENVIRONMENTBRDF)\n,sheenEnvironmentReflectance: vec3f\n#endif\n#endif\n};\n#define pbr_inline\nfn sheenBlock(\nvSheenColor: vec4f\n#ifdef SHEEN_ROUGHNESS\n,vSheenRoughness: f32\n#if defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE)\n,sheenMapRoughnessData: vec4f\n#endif\n#endif\n,roughness: f32\n#ifdef SHEEN_TEXTURE\n,sheenMapData: vec4f\n,sheenMapLevel: f32\n#endif\n,reflectance: f32\n#ifdef SHEEN_LINKWITHALBEDO\n,baseColor: vec3f\n,surfaceAlbedo: vec3f\n#endif\n#ifdef ENVIRONMENTBRDF\n,NdotV: f32\n,environmentBrdf: vec3f\n#endif\n#if defined(REFLECTION) && defined(ENVIRONMENTBRDF)\n,AARoughnessFactors: vec2f\n,vReflectionMicrosurfaceInfos: vec3f\n,vReflectionInfos: vec2f\n,vReflectionColor: vec3f\n,vLightingIntensity: vec4f\n#ifdef REFLECTIONMAP_3D\n,reflectionSampler: texture_cube<f32>\n,reflectionSamplerSampler: sampler\n,reflectionCoords: vec3f\n#else\n,reflectionSampler: texture_2d<f32>\n,reflectionSamplerSampler: sampler\n,reflectionCoords: vec2f\n#endif\n,NdotVUnclamped: f32\n#ifndef LODBASEDMICROSFURACE\n#ifdef REFLECTIONMAP_3D\n,reflectionLowSampler: texture_cube<f32>\n,reflectionLowSamplerSampler: sampler \n,reflectionHighSampler: texture_cube<f32>\n,reflectionHighSamplerSampler: sampler \n#else\n,reflectionLowSampler: texture_2d<f32>\n,reflectionLowSamplerSampler: sampler \n,reflectionHighSampler: texture_2d<f32>\n,reflectionHighSamplerSampler: sampler \n#endif\n#endif\n#ifdef REALTIME_FILTERING\n,vReflectionFilteringInfo: vec2f\n#endif\n#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION)\n,seo: f32\n#endif\n#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D)\n,eho: f32\n#endif\n#endif\n)->sheenOutParams\n{var outParams: sheenOutParams;var sheenIntensity: f32=vSheenColor.a;\n#ifdef SHEEN_TEXTURE\n#if DEBUGMODE>0\noutParams.sheenMapData=sheenMapData;\n#endif\n#endif\n#ifdef SHEEN_LINKWITHALBEDO\nvar sheenFactor: f32=pow5(1.0-sheenIntensity);var sheenColor: vec3f=baseColor.rgb*(1.0-sheenFactor);var sheenRoughness: f32=sheenIntensity;outParams.surfaceAlbedo=surfaceAlbedo*sheenFactor;\n#ifdef SHEEN_TEXTURE\nsheenIntensity*=sheenMapData.a;\n#endif\n#else\nvar sheenColor: vec3f=vSheenColor.rgb;\n#ifdef SHEEN_TEXTURE\n#ifdef SHEEN_GAMMATEXTURE\nsheenColor*=toLinearSpaceVec3(sheenMapData.rgb);\n#else\nsheenColor*=sheenMapData.rgb;\n#endif\nsheenColor*=sheenMapLevel;\n#endif\n#ifdef SHEEN_ROUGHNESS\nvar sheenRoughness: f32=vSheenRoughness;\n#ifdef SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE\n#if defined(SHEEN_TEXTURE)\nsheenRoughness*=sheenMapData.a;\n#endif\n#elif defined(SHEEN_TEXTURE_ROUGHNESS)\nsheenRoughness*=sheenMapRoughnessData.a;\n#endif\n#else\nvar sheenRoughness: f32=roughness;\n#ifdef SHEEN_TEXTURE\nsheenIntensity*=sheenMapData.a;\n#endif\n#endif\n#if !defined(SHEEN_ALBEDOSCALING)\nsheenIntensity*=(1.-reflectance);\n#endif\nsheenColor*=sheenIntensity;\n#endif\n#ifdef ENVIRONMENTBRDF\n/*#ifdef SHEEN_SOFTER\nvar environmentSheenBrdf: vec3f= vec3f(0.,0.,getBRDFLookupCharlieSheen(NdotV,sheenRoughness));\n#else*/\n#ifdef SHEEN_ROUGHNESS\nvar environmentSheenBrdf: vec3f=getBRDFLookup(NdotV,sheenRoughness);\n#else\nvar environmentSheenBrdf: vec3f=environmentBrdf;\n#endif\n/*#endif*/\n#endif\n#if defined(REFLECTION) && defined(ENVIRONMENTBRDF)\nvar sheenAlphaG: f32=convertRoughnessToAverageSlope(sheenRoughness);\n#ifdef SPECULARAA\nsheenAlphaG+=AARoughnessFactors.y;\n#endif\nvar environmentSheenRadiance: vec4f= vec4f(0.,0.,0.,0.);environmentSheenRadiance=sampleReflectionTexture(\nsheenAlphaG\n,vReflectionMicrosurfaceInfos\n,vReflectionInfos\n,vReflectionColor\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\n,NdotVUnclamped\n#endif\n#ifdef LINEARSPECULARREFLECTION\n,sheenRoughness\n#endif\n,reflectionSampler\n,reflectionSamplerSampler\n,reflectionCoords\n#ifndef LODBASEDMICROSFURACE\n,reflectionLowSampler\n,reflectionLowSamplerSampler\n,reflectionHighSampler\n,reflectionHighSamplerSampler\n#endif\n#ifdef REALTIME_FILTERING\n,vReflectionFilteringInfo\n#endif\n);var sheenEnvironmentReflectance: vec3f=getSheenReflectanceFromBRDFLookup(sheenColor,environmentSheenBrdf);\n#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION)\nsheenEnvironmentReflectance*=seo;\n#endif\n#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D)\nsheenEnvironmentReflectance*=eho;\n#endif\n#if DEBUGMODE>0\noutParams.sheenEnvironmentReflectance=sheenEnvironmentReflectance;\n#endif\noutParams.finalSheenRadianceScaled=\nenvironmentSheenRadiance.rgb *\nsheenEnvironmentReflectance *\nvLightingIntensity.z;\n#endif\n#if defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING)\noutParams.sheenAlbedoScaling=1.0-sheenIntensity*max(max(sheenColor.r,sheenColor.g),sheenColor.b)*environmentSheenBrdf.b;\n#endif\noutParams.sheenIntensity=sheenIntensity;outParams.sheenColor=sheenColor;outParams.sheenRoughness=sheenRoughness;return outParams;}\n#endif\n";Je.IncludesShadersStoreWGSL.pbrBlockClearcoat="struct clearcoatOutParams\n{specularEnvironmentR0: vec3f,\nconservationFactor: f32,\nclearCoatNormalW: vec3f,\nclearCoatAARoughnessFactors: vec2f,\nclearCoatIntensity: f32,\nclearCoatRoughness: f32,\n#ifdef REFLECTION\nfinalClearCoatRadianceScaled: vec3f,\n#endif\n#ifdef CLEARCOAT_TINT\nabsorption: vec3f,\nclearCoatNdotVRefract: f32,\nclearCoatColor: vec3f,\nclearCoatThickness: f32,\n#endif\n#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)\nenergyConservationFactorClearCoat: vec3f,\n#endif\n#if DEBUGMODE>0\n#ifdef CLEARCOAT_BUMP\nTBNClearCoat: mat3x3f,\n#endif\n#ifdef CLEARCOAT_TEXTURE\nclearCoatMapData: vec2f,\n#endif\n#if defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE)\nclearCoatTintMapData: vec4f,\n#endif\n#ifdef REFLECTION\nenvironmentClearCoatRadiance: vec4f,\nclearCoatEnvironmentReflectance: vec3f,\n#endif\nclearCoatNdotV: f32\n#endif\n};\n#ifdef CLEARCOAT\n#define pbr_inline\nfn clearcoatBlock(\nvPositionW: vec3f\n,geometricNormalW: vec3f\n,viewDirectionW: vec3f\n,vClearCoatParams: vec2f\n#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE)\n,clearCoatMapRoughnessData: vec4f\n#endif\n,specularEnvironmentR0: vec3f\n#ifdef CLEARCOAT_TEXTURE\n,clearCoatMapData: vec2f\n#endif\n#ifdef CLEARCOAT_TINT\n,vClearCoatTintParams: vec4f\n,clearCoatColorAtDistance: f32\n,vClearCoatRefractionParams: vec4f\n#ifdef CLEARCOAT_TINT_TEXTURE\n,clearCoatTintMapData: vec4f\n#endif\n#endif\n#ifdef CLEARCOAT_BUMP\n,vClearCoatBumpInfos: vec2f\n,clearCoatBumpMapData: vec4f\n,vClearCoatBumpUV: vec2f\n#if defined(TANGENT) && defined(NORMAL)\n,vTBN: mat3x3f\n#else\n,vClearCoatTangentSpaceParams: vec2f\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\n,normalMatrix: mat4x4f\n#endif\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\n,faceNormal: vec3f\n#endif\n#ifdef REFLECTION\n,vReflectionMicrosurfaceInfos: vec3f\n,vReflectionInfos: vec2f\n,vReflectionColor: vec3f\n,vLightingIntensity: vec4f\n#ifdef REFLECTIONMAP_3D\n,reflectionSampler: texture_cube<f32>\n,reflectionSamplerSampler: sampler\n#else\n,reflectionSampler: texture_2d<f32>\n,reflectionSamplerSampler: sampler\n#endif\n#ifndef LODBASEDMICROSFURACE\n#ifdef REFLECTIONMAP_3D\n,reflectionLowSampler: texture_cube<f32>\n,reflectionLowSamplerSampler: sampler \n,reflectionHighSampler: texture_cube<f32>\n,reflectionHighSamplerSampler: sampler \n#else\n,reflectionLowSampler: texture_2d<f32>\n,reflectionLowSamplerSampler: sampler \n,reflectionHighSampler: texture_2d<f32>\n,reflectionHighSamplerSampler: sampler \n#endif\n#endif\n#ifdef REALTIME_FILTERING\n,vReflectionFilteringInfo: vec2f\n#endif\n#endif\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n#ifdef RADIANCEOCCLUSION\n,ambientMonochrome: f32\n#endif\n#endif\n#if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING)\n,frontFacingMultiplier: f32\n#endif \n)->clearcoatOutParams\n{var outParams: clearcoatOutParams;var clearCoatIntensity: f32=vClearCoatParams.x;var clearCoatRoughness: f32=vClearCoatParams.y;\n#ifdef CLEARCOAT_TEXTURE\nclearCoatIntensity*=clearCoatMapData.x;\n#ifdef CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE\nclearCoatRoughness*=clearCoatMapData.y;\n#endif\n#if DEBUGMODE>0\noutParams.clearCoatMapData=clearCoatMapData;\n#endif\n#endif\n#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE)\nclearCoatRoughness*=clearCoatMapRoughnessData.y;\n#endif\noutParams.clearCoatIntensity=clearCoatIntensity;outParams.clearCoatRoughness=clearCoatRoughness;\n#ifdef CLEARCOAT_TINT\nvar clearCoatColor: vec3f=vClearCoatTintParams.rgb;var clearCoatThickness: f32=vClearCoatTintParams.a;\n#ifdef CLEARCOAT_TINT_TEXTURE\n#ifdef CLEARCOAT_TINT_GAMMATEXTURE\nclearCoatColor*=toLinearSpaceVec3(clearCoatTintMapData.rgb);\n#else\nclearCoatColor*=clearCoatTintMapData.rgb;\n#endif\nclearCoatThickness*=clearCoatTintMapData.a;\n#if DEBUGMODE>0\noutParams.clearCoatTintMapData=clearCoatTintMapData;\n#endif\n#endif\noutParams.clearCoatColor=computeColorAtDistanceInMedia(clearCoatColor,clearCoatColorAtDistance);outParams.clearCoatThickness=clearCoatThickness;\n#endif\n#ifdef CLEARCOAT_REMAP_F0\nvar specularEnvironmentR0Updated: vec3f=getR0RemappedForClearCoat(specularEnvironmentR0);\n#else\nvar specularEnvironmentR0Updated: vec3f=specularEnvironmentR0;\n#endif\noutParams.specularEnvironmentR0=mix(specularEnvironmentR0,specularEnvironmentR0Updated,clearCoatIntensity);var clearCoatNormalW: vec3f=geometricNormalW;\n#ifdef CLEARCOAT_BUMP\n#ifdef NORMALXYSCALE\nvar clearCoatNormalScale: f32=1.0;\n#else\nvar clearCoatNormalScale: f32=vClearCoatBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nvar TBNClearCoat: mat3x3f=vTBN;\n#else\nvar TBNClearCoatUV: vec2f=vClearCoatBumpUV*frontFacingMultiplier;var TBNClearCoat: mat3x3f=cotangent_frame(clearCoatNormalW*clearCoatNormalScale,vPositionW,TBNClearCoatUV,vClearCoatTangentSpaceParams);\n#endif\n#if DEBUGMODE>0\noutParams.TBNClearCoat=TBNClearCoat;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nclearCoatNormalW=normalize(clearCoatBumpMapData.xyz *2.0-1.0);clearCoatNormalW=normalize( mat3x3f(normalMatrix[0].xyz,normalMatrix[1].xyz,normalMatrix[2].xyz)*clearCoatNormalW);\n#else\nclearCoatNormalW=perturbNormal(TBNClearCoat,clearCoatBumpMapData.xyz,vClearCoatBumpInfos.y);\n#endif\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nclearCoatNormalW*=sign(dot(clearCoatNormalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nclearCoatNormalW=clearCoatNormalW*frontFacingMultiplier;\n#endif\noutParams.clearCoatNormalW=clearCoatNormalW;outParams.clearCoatAARoughnessFactors=getAARoughnessFactors(clearCoatNormalW.xyz);var clearCoatNdotVUnclamped: f32=dot(clearCoatNormalW,viewDirectionW);var clearCoatNdotV: f32=absEps(clearCoatNdotVUnclamped);\n#if DEBUGMODE>0\noutParams.clearCoatNdotV=clearCoatNdotV;\n#endif\n#ifdef CLEARCOAT_TINT\nvar clearCoatVRefract: vec3f=refract(-viewDirectionW,clearCoatNormalW,vClearCoatRefractionParams.y);outParams.clearCoatNdotVRefract=absEps(dot(clearCoatNormalW,clearCoatVRefract));\n#endif\n#if defined(ENVIRONMENTBRDF) && (!defined(REFLECTIONMAP_SKYBOX) || defined(MS_BRDF_ENERGY_CONSERVATION))\nvar environmentClearCoatBrdf: vec3f=getBRDFLookup(clearCoatNdotV,clearCoatRoughness);\n#endif\n#if defined(REFLECTION)\nvar clearCoatAlphaG: f32=convertRoughnessToAverageSlope(clearCoatRoughness);\n#ifdef SPECULARAA\nclearCoatAlphaG+=outParams.clearCoatAARoughnessFactors.y;\n#endif\nvar environmentClearCoatRadiance: vec4f= vec4f(0.,0.,0.,0.);var clearCoatReflectionVector: vec3f=computeReflectionCoords( vec4f(vPositionW,1.0),clearCoatNormalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nclearCoatReflectionVector.z*=-1.0;\n#endif\n#ifdef REFLECTIONMAP_3D\nvar clearCoatReflectionCoords: vec3f=clearCoatReflectionVector;\n#else\nvar clearCoatReflectionCoords: vec2f=clearCoatReflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nclearCoatReflectionCoords/=clearCoatReflectionVector.z;\n#endif\nclearCoatReflectionCoords.y=1.0-clearCoatReflectionCoords.y;\n#endif\nenvironmentClearCoatRadiance=sampleReflectionTexture(\nclearCoatAlphaG\n,vReflectionMicrosurfaceInfos\n,vReflectionInfos\n,vReflectionColor\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\n,clearCoatNdotVUnclamped\n#endif\n#ifdef LINEARSPECULARREFLECTION\n,clearCoatRoughness\n#endif\n,reflectionSampler\n,reflectionSamplerSampler\n,clearCoatReflectionCoords\n#ifndef LODBASEDMICROSFURACE\n,reflectionLowSampler\n,reflectionLowSamplerSampler\n,reflectionHighSampler\n,reflectionHighSamplerSampler\n#endif\n#ifdef REALTIME_FILTERING\n,vReflectionFilteringInfo\n#endif \n);\n#if DEBUGMODE>0\noutParams.environmentClearCoatRadiance=environmentClearCoatRadiance;\n#endif\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\nvar clearCoatEnvironmentReflectance: vec3f=getReflectanceFromBRDFLookup(vec3f(uniforms.vClearCoatRefractionParams.x),environmentClearCoatBrdf);\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nvar clearCoatEho: f32=environmentHorizonOcclusion(-viewDirectionW,clearCoatNormalW,geometricNormalW);clearCoatEnvironmentReflectance*=clearCoatEho;\n#endif\n#endif\n#endif\n#else\nvar clearCoatEnvironmentReflectance: vec3f=getReflectanceFromAnalyticalBRDFLookup_Jones(clearCoatNdotV, vec3f(1.), vec3f(1.),sqrt(1.-clearCoatRoughness));\n#endif\nclearCoatEnvironmentReflectance*=clearCoatIntensity;\n#if DEBUGMODE>0\noutParams.clearCoatEnvironmentReflectance=clearCoatEnvironmentReflectance;\n#endif\noutParams.finalClearCoatRadianceScaled=\nenvironmentClearCoatRadiance.rgb *\nclearCoatEnvironmentReflectance *\nvLightingIntensity.z;\n#endif\n#if defined(CLEARCOAT_TINT)\noutParams.absorption=computeClearCoatAbsorption(outParams.clearCoatNdotVRefract,outParams.clearCoatNdotVRefract,outParams.clearCoatColor,clearCoatThickness,clearCoatIntensity);\n#endif\nvar fresnelIBLClearCoat: f32=fresnelSchlickGGX(clearCoatNdotV,uniforms.vClearCoatRefractionParams.x,CLEARCOATREFLECTANCE90);fresnelIBLClearCoat*=clearCoatIntensity;outParams.conservationFactor=(1.-fresnelIBLClearCoat);\n#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)\noutParams.energyConservationFactorClearCoat=getEnergyConservationFactor(outParams.specularEnvironmentR0,environmentClearCoatBrdf);\n#endif\nreturn outParams;}\n#endif\n";Je.IncludesShadersStoreWGSL.pbrBlockIridescence="struct iridescenceOutParams\n{iridescenceIntensity: f32,\niridescenceIOR: f32,\niridescenceThickness: f32,\nspecularEnvironmentR0: vec3f};\n#ifdef IRIDESCENCE\nfn iridescenceBlock(\nvIridescenceParams: vec4f\n,viewAngle: f32\n,specularEnvironmentR0: vec3f\n#ifdef IRIDESCENCE_TEXTURE\n,iridescenceMapData: vec2f\n#endif\n#ifdef IRIDESCENCE_THICKNESS_TEXTURE\n,iridescenceThicknessMapData: vec2f\n#endif\n#ifdef CLEARCOAT\n,NdotVUnclamped: f32\n#ifdef CLEARCOAT_TEXTURE\n,clearCoatMapData: vec2f\n#endif\n#endif\n)->iridescenceOutParams\n{var outParams: iridescenceOutParams;var iridescenceIntensity: f32=vIridescenceParams.x;var iridescenceIOR: f32=vIridescenceParams.y;var iridescenceThicknessMin: f32=vIridescenceParams.z;var iridescenceThicknessMax: f32=vIridescenceParams.w;var iridescenceThicknessWeight: f32=1.;\n#ifdef IRIDESCENCE_TEXTURE\niridescenceIntensity*=iridescenceMapData.x;\n#endif\n#if defined(IRIDESCENCE_THICKNESS_TEXTURE)\niridescenceThicknessWeight=iridescenceThicknessMapData.g;\n#endif\nvar iridescenceThickness: f32=mix(iridescenceThicknessMin,iridescenceThicknessMax,iridescenceThicknessWeight);var topIor: f32=1.; \n#ifdef CLEARCOAT\nvar clearCoatIntensity: f32=vClearCoatParams.x;\n#ifdef CLEARCOAT_TEXTURE\nclearCoatIntensity*=clearCoatMapData.x;\n#endif\ntopIor=mix(1.0,uniforms.vClearCoatRefractionParams.w-1.,clearCoatIntensity);viewAngle=sqrt(1.0+((1.0/topIor)*(1.0/topIor))*((NdotVUnclamped*NdotVUnclamped)-1.0));\n#endif\nvar iridescenceFresnel: vec3f=evalIridescence(topIor,iridescenceIOR,viewAngle,iridescenceThickness,specularEnvironmentR0);outParams.specularEnvironmentR0=mix(specularEnvironmentR0,iridescenceFresnel,iridescenceIntensity);outParams.iridescenceIntensity=iridescenceIntensity;outParams.iridescenceThickness=iridescenceThickness;outParams.iridescenceIOR=iridescenceIOR;return outParams;}\n#endif\n";Je.IncludesShadersStoreWGSL.pbrBlockSubSurface="struct subSurfaceOutParams\n{specularEnvironmentReflectance: vec3f,\n#ifdef SS_REFRACTION\nfinalRefraction: vec3f,\nsurfaceAlbedo: vec3f,\n#ifdef SS_LINKREFRACTIONTOTRANSPARENCY\nalpha: f32,\n#endif\n#ifdef REFLECTION\nrefractionFactorForIrradiance: f32,\n#endif\n#endif\n#ifdef SS_TRANSLUCENCY\ntransmittance: vec3f,\ntranslucencyIntensity: f32,\n#ifdef REFLECTION\nrefractionIrradiance: vec3f,\n#endif\n#endif\n#if DEBUGMODE>0\n#ifdef SS_THICKNESSANDMASK_TEXTURE\nthicknessMap: vec4f,\n#endif\n#ifdef SS_REFRACTION\nenvironmentRefraction: vec4f,\nrefractionTransmittance: vec3f\n#endif\n#endif\n};\n#ifdef SUBSURFACE\n#ifdef SS_REFRACTION\n#define pbr_inline\nfn sampleEnvironmentRefraction(\nior: f32\n,thickness: f32\n,refractionLOD: f32\n,normalW: vec3f\n,vPositionW: vec3f\n,viewDirectionW: vec3f\n,view: mat4x4f\n,vRefractionInfos: vec4f\n,refractionMatrix: mat4x4f\n,vRefractionMicrosurfaceInfos: vec4f\n,alphaG: f32\n#ifdef SS_REFRACTIONMAP_3D\n,refractionSampler: texture_cube<f32>\n,refractionSamplerSampler: sampler\n#ifndef LODBASEDMICROSFURACE\n,refractionLowSampler: texture_cube<f32>\n,refractionLowSamplerSampler: sampler\n,refractionHighSampler: texture_cube<f32>\n,refractionHighSamplerSampler: sampler \n#endif\n#else\n,refractionSampler: texture_2d<f32>\n,refractionSamplerSampler: sampler\n#ifndef LODBASEDMICROSFURACE\n,refractionLowSampler: texture_2d<f32>\n,refractionLowSamplerSampler: sampler\n,refractionHighSampler: texture_2d<f32>\n,refractionHighSamplerSampler: sampler \n#endif\n#endif\n#ifdef ANISOTROPIC\n,anisotropicOut: anisotropicOutParams\n#endif\n#ifdef REALTIME_FILTERING\n,vRefractionFilteringInfo: vec2f\n#endif\n#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC\n,refractionPosition: vec3f\n,refractionSize: vec3f\n#endif\n)->vec4f {var environmentRefraction: vec4f= vec4f(0.,0.,0.,0.);\n#ifdef ANISOTROPIC\nvar refractionVector: vec3f=refract(-viewDirectionW,anisotropicOut.anisotropicNormal,ior);\n#else\nvar refractionVector: vec3f=refract(-viewDirectionW,normalW,ior);\n#endif\n#ifdef SS_REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n#ifdef SS_REFRACTIONMAP_3D\n#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC\nrefractionVector=parallaxCorrectNormal(vPositionW,refractionVector,refractionSize,refractionPosition);\n#endif\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;var refractionCoords: vec3f=refractionVector;refractionCoords= (refractionMatrix* vec4f(refractionCoords,0)).xyz;\n#else\n#ifdef SS_USE_THICKNESS_AS_DEPTH\nvar vRefractionUVW: vec3f= (refractionMatrix*(view* vec4f(vPositionW+refractionVector*thickness,1.0))).xyz;\n#else\nvar vRefractionUVW: vec3f= (refractionMatrix*(view* vec4f(vPositionW+refractionVector*vRefractionInfos.z,1.0))).xyz;\n#endif\nvar refractionCoords: vec2f=vRefractionUVW.xy/vRefractionUVW.z;refractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODBASEDMICROSFURACE\nvar lod=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef SS_LODINREFRACTIONALPHA\nvar automaticRefractionLOD: f32=UNPACK_LOD(textureSample(refractionSampler,refractionSamplerSampler,refractionCoords).a);var requestedRefractionLOD: f32=max(automaticRefractionLOD,lod);\n#else\nvar requestedRefractionLOD: f32=lod;\n#endif\n#if defined(REALTIME_FILTERING) && defined(SS_REFRACTIONMAP_3D)\nenvironmentRefraction= vec4f(radiance(alphaG,refractionSampler,refractionSamplerSampler,refractionCoords,vRefractionFilteringInfo),1.0);\n#else\nenvironmentRefraction=textureSampleLevel(refractionSampler,refractionSamplerSampler,refractionCoords,requestedRefractionLOD);\n#endif\n#else\nvar lodRefractionNormalized: f32=saturate(refractionLOD/log2(vRefractionMicrosurfaceInfos.x));var lodRefractionNormalizedDoubled: f32=lodRefractionNormalized*2.0;var environmentRefractionMid: vec4f=textureSample(refractionSampler,refractionSamplerSampler,refractionCoords);if (lodRefractionNormalizedDoubled<1.0){environmentRefraction=mix(\ntextureSample(refractionHighSampler,refractionHighSamplerSampler,refractionCoords),\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);} else {environmentRefraction=mix(\nenvironmentRefractionMid,\ntextureSample(refractionLowSampler,refractionLowSamplerSampler,refractionCoords),\nlodRefractionNormalizedDoubled-1.0\n);}\n#endif\nvar refraction=environmentRefraction.rgb;\n#ifdef SS_RGBDREFRACTION\nrefraction=fromRGBD(environmentRefraction);\n#endif\n#ifdef SS_GAMMAREFRACTION\nrefraction=toLinearSpaceVec3(environmentRefraction.rgb);\n#endif\nreturn vec4f(refraction,environmentRefraction.a);}\n#endif\n#define pbr_inline\nfn subSurfaceBlock(\nvSubSurfaceIntensity: vec3f\n,vThicknessParam: vec2f\n,vTintColor: vec4f\n,normalW: vec3f\n,specularEnvironmentReflectance: vec3f\n#ifdef SS_THICKNESSANDMASK_TEXTURE\n,thicknessMap: vec4f\n#endif\n#ifdef SS_REFRACTIONINTENSITY_TEXTURE\n,refractionIntensityMap: vec4f\n#endif\n#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE\n,translucencyIntensityMap: vec4f\n#endif\n#ifdef REFLECTION\n#ifdef SS_TRANSLUCENCY\n,reflectionMatrix: mat4x4f\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)\n,irradianceVector_: vec3f\n#endif\n#if defined(REALTIME_FILTERING)\n,reflectionSampler: texture_cube<f32>\n,reflectionSamplerSampler: sampler\n,vReflectionFilteringInfo: vec2f\n#endif\n#endif\n#ifdef USEIRRADIANCEMAP\n#ifdef REFLECTIONMAP_3D\n,irradianceSampler: texture_cube<f32>\n,irradianceSamplerSampler: sampler\n#else\n,irradianceSampler: texture_2d<f32>\n,irradianceSamplerSampler: sampler\n#endif\n#endif\n#endif\n#endif\n#if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY)\n,surfaceAlbedo: vec3f\n#endif\n#ifdef SS_REFRACTION\n,vPositionW: vec3f\n,viewDirectionW: vec3f\n,view: mat4x4f\n,vRefractionInfos: vec4f\n,refractionMatrix: mat4x4f\n,vRefractionMicrosurfaceInfos: vec4f\n,vLightingIntensity: vec4f\n#ifdef SS_LINKREFRACTIONTOTRANSPARENCY\n,alpha: f32\n#endif\n#ifdef SS_LODINREFRACTIONALPHA\n,NdotVUnclamped: f32\n#endif\n#ifdef SS_LINEARSPECULARREFRACTION\n,roughness: f32\n#endif\n,alphaG: f32\n#ifdef SS_REFRACTIONMAP_3D\n,refractionSampler: texture_cube<f32>\n,refractionSamplerSampler: sampler\n#ifndef LODBASEDMICROSFURACE\n,refractionLowSampler: texture_cube<f32>\n,refractionLowSamplerSampler: sampler\n,refractionHighSampler: texture_cube<f32>\n,refractionHighSamplerSampler: sampler \n#endif\n#else\n,refractionSampler: texture_2d<f32>\n,refractionSamplerSampler: sampler\n#ifndef LODBASEDMICROSFURACE\n,refractionLowSampler: texture_2d<f32>\n,refractionLowSamplerSampler: sampler\n,refractionHighSampler: texture_2d<f32>\n,refractionHighSamplerSampler: sampler \n#endif\n#endif\n#ifdef ANISOTROPIC\n,anisotropicOut: anisotropicOutParams\n#endif\n#ifdef REALTIME_FILTERING\n,vRefractionFilteringInfo: vec2f\n#endif\n#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC\n,refractionPosition: vec3f\n,refractionSize: vec3f\n#endif\n#ifdef SS_DISPERSION\n,dispersion: f32\n#endif\n#endif\n#ifdef SS_TRANSLUCENCY\n,vDiffusionDistance: vec3f\n,vTranslucencyColor: vec4f\n#ifdef SS_TRANSLUCENCYCOLOR_TEXTURE\n,translucencyColorMap: vec4f\n#endif\n#endif\n)->subSurfaceOutParams\n{var outParams: subSurfaceOutParams;outParams.specularEnvironmentReflectance=specularEnvironmentReflectance;\n#ifdef SS_REFRACTION\nvar refractionIntensity: f32=vSubSurfaceIntensity.x;\n#ifdef SS_LINKREFRACTIONTOTRANSPARENCY\nrefractionIntensity*=(1.0-alpha);outParams.alpha=1.0;\n#endif\n#endif\n#ifdef SS_TRANSLUCENCY\nvar translucencyIntensity: f32=vSubSurfaceIntensity.y;\n#endif\n#ifdef SS_THICKNESSANDMASK_TEXTURE\n#ifdef SS_USE_GLTF_TEXTURES\nvar thickness: f32=thicknessMap.g*vThicknessParam.y+vThicknessParam.x;\n#else\nvar thickness: f32=thicknessMap.r*vThicknessParam.y+vThicknessParam.x;\n#endif\n#if DEBUGMODE>0\noutParams.thicknessMap=thicknessMap;\n#endif\n#if defined(SS_REFRACTION) && defined(SS_REFRACTION_USE_INTENSITY_FROM_THICKNESS)\n#ifdef SS_USE_GLTF_TEXTURES\nrefractionIntensity*=thicknessMap.r;\n#else\nrefractionIntensity*=thicknessMap.g;\n#endif\n#endif\n#if defined(SS_TRANSLUCENCY) && defined(SS_TRANSLUCENCY_USE_INTENSITY_FROM_THICKNESS)\n#ifdef SS_USE_GLTF_TEXTURES\ntranslucencyIntensity*=thicknessMap.a;\n#else\ntranslucencyIntensity*=thicknessMap.b;\n#endif\n#endif\n#else\nvar thickness: f32=vThicknessParam.y;\n#endif\n#if defined(SS_REFRACTION) && defined(SS_REFRACTIONINTENSITY_TEXTURE)\n#ifdef SS_USE_GLTF_TEXTURES\nrefractionIntensity*=refractionIntensityMap.r;\n#else\nrefractionIntensity*=refractionIntensityMap.g;\n#endif\n#endif\n#if defined(SS_TRANSLUCENCY) && defined(SS_TRANSLUCENCYINTENSITY_TEXTURE)\n#ifdef SS_USE_GLTF_TEXTURES\ntranslucencyIntensity*=translucencyIntensityMap.a;\n#else\ntranslucencyIntensity*=translucencyIntensityMap.b;\n#endif\n#endif\n#ifdef SS_TRANSLUCENCY\nthickness=maxEps(thickness);var translucencyColor: vec4f=vTranslucencyColor;\n#ifdef SS_TRANSLUCENCYCOLOR_TEXTURE\ntranslucencyColor*=translucencyColorMap;\n#endif\nvar transmittance: vec3f=transmittanceBRDF_Burley(translucencyColor.rgb,vDiffusionDistance,thickness);transmittance*=translucencyIntensity;outParams.transmittance=transmittance;outParams.translucencyIntensity=translucencyIntensity;\n#endif\n#ifdef SS_REFRACTION\nvar environmentRefraction: vec4f= vec4f(0.,0.,0.,0.);\n#ifdef SS_HAS_THICKNESS\nvar ior: f32=vRefractionInfos.y;\n#else\nvar ior: f32=vRefractionMicrosurfaceInfos.w;\n#endif\n#ifdef SS_LODINREFRACTIONALPHA\nvar refractionAlphaG: f32=alphaG;refractionAlphaG=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));var refractionLOD: f32=getLodFromAlphaGNdotV(vRefractionMicrosurfaceInfos.x,refractionAlphaG,NdotVUnclamped);\n#elif defined(SS_LINEARSPECULARREFRACTION)\nvar refractionRoughness: f32=alphaG;refractionRoughness=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));var refractionLOD: f32=getLinearLodFromRoughness(vRefractionMicrosurfaceInfos.x,refractionRoughness);\n#else\nvar refractionAlphaG: f32=alphaG;refractionAlphaG=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));var refractionLOD: f32=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,refractionAlphaG);\n#endif\nvar refraction_ior: f32=vRefractionInfos.y;\n#ifdef SS_DISPERSION\nvar realIOR: f32=1.0/refraction_ior;var iorDispersionSpread: f32=0.04*dispersion*(realIOR-1.0);var iors: vec3f= vec3f(1.0/(realIOR-iorDispersionSpread),refraction_ior,1.0/(realIOR+iorDispersionSpread));for (var i: i32=0; i<3; i++) {refraction_ior=iors[i];\n#endif\nvar envSample: vec4f=sampleEnvironmentRefraction(refraction_ior,thickness,refractionLOD,normalW,vPositionW,viewDirectionW,view,vRefractionInfos,refractionMatrix,vRefractionMicrosurfaceInfos,alphaG\n#ifdef SS_REFRACTIONMAP_3D\n,refractionSampler\n,refractionSamplerSampler\n#ifndef LODBASEDMICROSFURACE\n,refractionLowSampler\n,refractionLowSamplerSampler\n,refractionHighSampler\n,refractionHighSamplerSampler\n#endif\n#else\n,refractionSampler\n,refractionSamplerSampler\n#ifndef LODBASEDMICROSFURACE\n,refractionLowSampler\n,refractionLowSamplerSampler\n,refractionHighSampler\n,refractionHighSamplerSampler\n#endif\n#endif\n#ifdef ANISOTROPIC\n,anisotropicOut\n#endif\n#ifdef REALTIME_FILTERING\n,vRefractionFilteringInfo\n#endif\n#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC\n,refractionPosition\n,refractionSize\n#endif\n);\n#ifdef SS_DISPERSION\nenvironmentRefraction[i]=envSample[i];}\n#else\nenvironmentRefraction=envSample;\n#endif\nenvironmentRefraction=vec4f(environmentRefraction.rgb*vRefractionInfos.x,environmentRefraction.a);\n#endif\n#ifdef SS_REFRACTION\nvar refractionTransmittance: vec3f= vec3f(refractionIntensity);\n#ifdef SS_THICKNESSANDMASK_TEXTURE\nvar volumeAlbedo: vec3f=computeColorAtDistanceInMedia(vTintColor.rgb,vTintColor.w);refractionTransmittance*=cocaLambertVec3(volumeAlbedo,thickness);\n#elif defined(SS_LINKREFRACTIONTOTRANSPARENCY)\nvar maxChannel: f32=max(max(surfaceAlbedo.r,surfaceAlbedo.g),surfaceAlbedo.b);var volumeAlbedo: vec3f=saturateVec3(maxChannel*surfaceAlbedo);environmentRefraction=vec4f(environmentRefraction.rgb*volumeAlbedo,environmentRefraction.a);\n#else\nvar volumeAlbedo: vec3f=computeColorAtDistanceInMedia(vTintColor.rgb,vTintColor.w);refractionTransmittance*=cocaLambertVec3(volumeAlbedo,vThicknessParam.y);\n#endif\n#ifdef SS_ALBEDOFORREFRACTIONTINT\nenvironmentRefraction=vec4f(environmentRefraction.rgb*surfaceAlbedo.rgb,environmentRefraction.a);\n#endif\noutParams.surfaceAlbedo=surfaceAlbedo*(1.-refractionIntensity);\n#ifdef REFLECTION\noutParams.refractionFactorForIrradiance=(1.-refractionIntensity);\n#endif\n#ifdef UNUSED_MULTIPLEBOUNCES\nvar bounceSpecularEnvironmentReflectance: vec3f=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);outParams.specularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,refractionIntensity);\n#endif\nrefractionTransmittance*=1.0-outParams.specularEnvironmentReflectance;\n#if DEBUGMODE>0\noutParams.refractionTransmittance=refractionTransmittance;\n#endif\noutParams.finalRefraction=environmentRefraction.rgb*refractionTransmittance*vLightingIntensity.z;\n#if DEBUGMODE>0\noutParams.environmentRefraction=environmentRefraction;\n#endif\n#endif\n#if defined(REFLECTION) && defined(SS_TRANSLUCENCY)\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX) || !defined(USESPHERICALFROMREFLECTIONMAP)\nvar irradianceVector: vec3f= (reflectionMatrix* vec4f(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\n#ifdef INVERTCUBICMAP\nirradianceVector.y*=-1.0;\n#endif\n#else\nvar irradianceVector: vec3f=irradianceVector_;\n#endif\n#if defined(USESPHERICALFROMREFLECTIONMAP)\n#if defined(REALTIME_FILTERING)\nvar refractionIrradiance: vec3f=irradiance(reflectionSampler,reflectionSamplerSampler,-irradianceVector,vReflectionFilteringInfo);\n#else\nvar refractionIrradiance: vec3f=computeEnvironmentIrradiance(-irradianceVector);\n#endif\n#elif defined(USEIRRADIANCEMAP)\n#ifdef REFLECTIONMAP_3D\nvar irradianceCoords: vec3f=irradianceVector;\n#else\nvar irradianceCoords: vec2f=irradianceVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nirradianceCoords/=irradianceVector.z;\n#endif\nirradianceCoords.y=1.0-irradianceCoords.y;\n#endif\nvar temp: vec4f=textureSample(irradianceSampler,irradianceSamplerSampler,-irradianceCoords);var refractionIrradiance=temp.rgb;\n#ifdef RGBDREFLECTION\nrefractionIrradiance=fromRGBD(temp).rgb;\n#endif\n#ifdef GAMMAREFLECTION\nrefractionIrradiance=toLinearSpaceVec3(refractionIrradiance);\n#endif\n#else\nvar refractionIrradiance: vec3f= vec3f(0.);\n#endif\nrefractionIrradiance*=transmittance;\n#ifdef SS_ALBEDOFORTRANSLUCENCYTINT\nrefractionIrradiance*=surfaceAlbedo.rgb;\n#endif\noutParams.refractionIrradiance=refractionIrradiance;\n#endif\nreturn outParams;}\n#endif\n";Je.IncludesShadersStoreWGSL.clipPlaneFragment="#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";Je.IncludesShadersStoreWGSL.pbrBlockNormalGeometric="var viewDirectionW: vec3f=normalize(scene.vEyePosition.xyz-input.vPositionW);\n#ifdef NORMAL\nvar normalW: vec3f=normalize(input.vNormalW);\n#else\nvar normalW: vec3f=normalize(cross(dpdx(input.vPositionW),dpdy(input.vPositionW)))*scene.vEyePosition.w;\n#endif\nvar geometricNormalW: vec3f=normalW;\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\ngeometricNormalW=select(-geometricNormalW,geometricNormalW,fragmentInputs.frontFacing);\n#endif\n";Je.IncludesShadersStoreWGSL.bumpFragment="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<f32>(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<f32>(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";Je.IncludesShadersStoreWGSL.pbrBlockNormalFinal="#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvar faceNormal: vec3f=normalize(cross(dpdx(fragmentInputs.vPositionW),dpdy(fragmentInputs.vPositionW)))*scene.vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=select(-faceNormal,faceNormal,fragmentInputs.frontFacing);\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=select(-normalW,normalW,fragmentInputs.frontFacing);\n#endif\n";Je.IncludesShadersStoreWGSL.depthPrePass="#ifdef DEPTHPREPASS\nfragmentOutputs.color= vec4f(0.,0.,0.,1.0);return fragmentOutputs;\n#endif\n";Je.IncludesShadersStoreWGSL.pbrBlockLightmapInit="#ifdef LIGHTMAP\nvar lightmapColor: vec4f=textureSample(lightmapSampler,lightmapSamplerSampler,fragmentInputs.vLightmapUV+uvOffset);\n#ifdef RGBDLIGHTMAP\nlightmapColor=vec4f(fromRGBD(lightmapColor),lightmapColor.a);\n#endif\n#ifdef GAMMALIGHTMAP\nlightmapColor=vec4f(toLinearSpaceVec3(lightmapColor.rgb),lightmapColor.a);\n#endif\nlightmapColor=vec4f(lightmapColor.rgb*uniforms.vLightmapInfos.y,lightmapColor.a);\n#endif\n";Je.IncludesShadersStoreWGSL.pbrBlockGeometryInfo="var NdotVUnclamped: f32=dot(normalW,viewDirectionW);var NdotV: f32=absEps(NdotVUnclamped);var alphaG: f32=convertRoughnessToAverageSlope(roughness);var AARoughnessFactors: vec2f=getAARoughnessFactors(normalW.xyz);\n#ifdef SPECULARAA\nalphaG+=AARoughnessFactors.y;\n#endif\n#if defined(ENVIRONMENTBRDF)\nvar environmentBrdf: vec3f=getBRDFLookup(NdotV,roughness);\n#endif\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nvar ambientMonochrome: f32=aoOut.ambientOcclusionColor.r;\n#else\nvar ambientMonochrome: f32=getLuminance(aoOut.ambientOcclusionColor);\n#endif\nvar seo: f32=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nvar eho: f32=environmentHorizonOcclusion(-viewDirectionW,normalW,geometricNormalW);\n#endif\n#endif\n#endif\n#endif\n";Je.IncludesShadersStoreWGSL.pbrBlockReflectance0="var reflectance: f32=max(max(reflectivityOut.surfaceReflectivityColor.r,reflectivityOut.surfaceReflectivityColor.g),reflectivityOut.surfaceReflectivityColor.b);var specularEnvironmentR0: vec3f=reflectivityOut.surfaceReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvar specularEnvironmentR90: vec3f= vec3f(metallicReflectanceFactors.a);\n#else \nvar specularEnvironmentR90: vec3f= vec3f(1.0,1.0,1.0);\n#endif\n#ifdef ALPHAFRESNEL\nvar reflectance90: f32=fresnelGrazingReflectance(reflectance);specularEnvironmentR90=specularEnvironmentR90*reflectance90;\n#endif\n";Je.IncludesShadersStoreWGSL.pbrBlockReflectance="#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\nvar specularEnvironmentReflectance: vec3f=getReflectanceFromBRDFWithEnvLookup(clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,environmentBrdf);\n#ifdef RADIANCEOCCLUSION\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\nvar specularEnvironmentReflectance: vec3f=getReflectanceFromAnalyticalBRDFLookup_Jones(NdotV,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n#ifdef CLEARCOAT\nspecularEnvironmentReflectance*=clearcoatOut.conservationFactor;\n#if defined(CLEARCOAT_TINT)\nspecularEnvironmentReflectance*=clearcoatOut.absorption;\n#endif\n#endif\n";Je.IncludesShadersStoreWGSL.pbrBlockDirectLighting="var diffuseBase: vec3f=vec3f(0.,0.,0.);\n#ifdef SPECULARTERM\nvar specularBase: vec3f=vec3f(0.,0.,0.);\n#endif\n#ifdef CLEARCOAT\nvar clearCoatBase: vec3f=vec3f(0.,0.,0.);\n#endif\n#ifdef SHEEN\nvar sheenBase: vec3f=vec3f(0.,0.,0.);\n#endif\nvar preInfo: preLightingInfo;var info: lightingInfo;var shadow: f32=1.; \nvar aggShadow: f32=0.;var numLights: f32=0.;\n#if defined(CLEARCOAT) && defined(CLEARCOAT_TINT)\nvar absorption: vec3f=vec3f(0.);\n#endif\n";Je.IncludesShadersStoreWGSL.lightFragment="#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\npreInfo=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW,input.vPositionW);\n#elif defined(POINTLIGHT{X})\npreInfo=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW,input.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,light{X}.vLightDiffuse.rgb,light{X}.vLightGround);\n#elif defined(SS_TRANSLUCENCY)\ninfo.diffuse=computeDiffuseAndTransmittedLighting(preInfo,light{X}.vLightDiffuse.rgb,subSurfaceOut.transmittance);\n#else\ninfo.diffuse=computeDiffuseLighting(preInfo,light{X}.vLightDiffuse.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,light{X}.vLightDiffuse.rgb);\n#else\ninfo.specular=computeSpecularLighting(preInfo,normalW,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.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,light{X}.vLightDiffuse.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,light{X}.vLightDiffuse.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,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightDiffuse.a,glossiness);\n#elif defined(HEMILIGHT{X})\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightGround,glossiness);\n#elif defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightTexture{X},projectionLightTexture{X}Sampler,uniforms.textureProjectionMatrix{X},input.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<SHADOWCSMNUM_CASCADES{X}; i++) \n{\n#ifdef SHADOWCSM_RIGHTHANDED{X}\ndiff{X}=uniforms.viewFrustumZ{X}[i]+fragmentInputs.vPositionFromCamera{X}.z;\n#else\ndiff{X}=uniforms.viewFrustumZ{X}[i]-fragmentInputs.vPositionFromCamera{X}.z;\n#endif\nif (diff{X}>=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(input.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(input.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(input.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(input.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";Je.IncludesShadersStoreWGSL.pbrBlockFinalLitComponents="aggShadow=aggShadow/numLights;\n#if defined(ENVIRONMENTBRDF)\n#ifdef MS_BRDF_ENERGY_CONSERVATION\nvar energyConservationFactor: vec3f=getEnergyConservationFactor(clearcoatOut.specularEnvironmentR0,environmentBrdf);\n#endif\n#endif\n#ifndef METALLICWORKFLOW\n#ifdef SPECULAR_GLOSSINESS_ENERGY_CONSERVATION\nsurfaceAlbedo=(1.-reflectance)*surfaceAlbedo.rgb;\n#endif\n#endif\n#if defined(SHEEN) && defined(SHEEN_ALBEDOSCALING) && defined(ENVIRONMENTBRDF)\nsurfaceAlbedo=sheenOut.sheenAlbedoScaling*surfaceAlbedo.rgb;\n#endif\n#ifdef REFLECTION\nvar finalIrradiance: vec3f=reflectionOut.environmentIrradiance;\n#if defined(CLEARCOAT)\nfinalIrradiance*=clearcoatOut.conservationFactor;\n#if defined(CLEARCOAT_TINT)\nfinalIrradiance*=clearcoatOut.absorption;\n#endif\n#endif\n#if defined(SS_REFRACTION)\nfinalIrradiance*=subSurfaceOut.refractionFactorForIrradiance;\n#endif\n#if defined(SS_TRANSLUCENCY)\nfinalIrradiance*=(1.0-subSurfaceOut.translucencyIntensity);finalIrradiance+=subSurfaceOut.refractionIrradiance;\n#endif\nfinalIrradiance*=surfaceAlbedo.rgb;finalIrradiance*=uniforms.vLightingIntensity.z;finalIrradiance*=aoOut.ambientOcclusionColor;\n#endif\n#ifdef SPECULARTERM\nvar finalSpecular: vec3f=specularBase;finalSpecular=max(finalSpecular,vec3f(0.0));var finalSpecularScaled: vec3f=finalSpecular*uniforms.vLightingIntensity.x*uniforms.vLightingIntensity.w;\n#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)\nfinalSpecularScaled*=energyConservationFactor;\n#endif\n#if defined(SHEEN) && defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING)\nfinalSpecularScaled*=sheenOut.sheenAlbedoScaling;\n#endif\n#endif\n#ifdef REFLECTION\nvar finalRadiance: vec3f=reflectionOut.environmentRadiance.rgb;finalRadiance*=subSurfaceOut.specularEnvironmentReflectance;var finalRadianceScaled: vec3f=finalRadiance*uniforms.vLightingIntensity.z;\n#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)\nfinalRadianceScaled*=energyConservationFactor;\n#endif\n#if defined(SHEEN) && defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING)\nfinalRadianceScaled*=sheenOut.sheenAlbedoScaling;\n#endif\n#endif\n#ifdef SHEEN\nvar finalSheen: vec3f=sheenBase*sheenOut.sheenColor;finalSheen=max(finalSheen,vec3f(0.0));var finalSheenScaled: vec3f=finalSheen*uniforms.vLightingIntensity.x*uniforms.vLightingIntensity.w;\n#if defined(CLEARCOAT) && defined(REFLECTION) && defined(ENVIRONMENTBRDF)\nsheenOut.finalSheenRadianceScaled*=clearcoatOut.conservationFactor;\n#if defined(CLEARCOAT_TINT)\nsheenOut.finalSheenRadianceScaled*=clearcoatOut.absorption;\n#endif\n#endif\n#endif\n#ifdef CLEARCOAT\nvar finalClearCoat: vec3f=clearCoatBase;finalClearCoat=max(finalClearCoat,vec3f(0.0));var finalClearCoatScaled: vec3f=finalClearCoat*uniforms.vLightingIntensity.x*uniforms.vLightingIntensity.w;\n#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)\nfinalClearCoatScaled*=clearcoatOut.energyConservationFactorClearCoat;\n#endif\n#ifdef SS_REFRACTION\nsubSurfaceOut.finalRefraction*=clearcoatOut.conservationFactor;\n#ifdef CLEARCOAT_TINT\nsubSurfaceOut.finalRefraction*=clearcoatOut.absorption;\n#endif\n#endif\n#endif\n#ifdef ALPHABLEND\nvar luminanceOverAlpha: f32=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#if defined(CLEARCOAT)\nluminanceOverAlpha+=getLuminance(clearcoatOut.finalClearCoatRadianceScaled);\n#endif\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(CLEARCOAT) && defined(CLEARCOATOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalClearCoatScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA) || defined(CLEARCOATOVERALPHA)\nalpha=saturate(alpha+luminanceOverAlpha*luminanceOverAlpha);\n#endif\n#endif\n";Je.IncludesShadersStoreWGSL.pbrBlockFinalUnlitComponents="var finalDiffuse: vec3f=diffuseBase;finalDiffuse*=surfaceAlbedo.rgb;finalDiffuse=max(finalDiffuse,vec3f(0.0));finalDiffuse*=uniforms.vLightingIntensity.x;var finalAmbient: vec3f=uniforms.vAmbientColor;finalAmbient*=surfaceAlbedo.rgb;var finalEmissive: vec3f=uniforms.vEmissiveColor;\n#ifdef EMISSIVE\nvar emissiveColorTex: vec3f=textureSample(emissiveSampler,emissiveSamplerSampler,fragmentInputs.vEmissiveUV+uvOffset).rgb;\n#ifdef GAMMAEMISSIVE\nfinalEmissive*=toLinearSpaceVec3(emissiveColorTex.rgb);\n#else\nfinalEmissive*=emissiveColorTex.rgb;\n#endif\nfinalEmissive*= uniforms.vEmissiveInfos.y;\n#endif\nfinalEmissive*=uniforms.vLightingIntensity.y;\n#ifdef AMBIENT\nvar ambientOcclusionForDirectDiffuse: vec3f=mix( vec3f(1.),aoOut.ambientOcclusionColor,uniforms.vAmbientInfos.w);\n#else\nvar ambientOcclusionForDirectDiffuse: vec3f=aoOut.ambientOcclusionColor;\n#endif\nfinalAmbient*=aoOut.ambientOcclusionColor;finalDiffuse*=ambientOcclusionForDirectDiffuse;\n";Je.IncludesShadersStoreWGSL.pbrBlockFinalColorComposition="var finalColor: vec4f= vec4f(\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance +\n#endif\n#ifdef SPECULARTERM\nfinalSpecularScaled +\n#endif\n#ifdef SHEEN\nfinalSheenScaled +\n#endif\n#ifdef CLEARCOAT\nfinalClearCoatScaled +\n#endif\n#ifdef REFLECTION\nfinalRadianceScaled +\n#if defined(SHEEN) && defined(ENVIRONMENTBRDF)\nsheenOut.finalSheenRadianceScaled +\n#endif\n#ifdef CLEARCOAT\nclearcoatOut.finalClearCoatRadianceScaled +\n#endif\n#endif\n#ifdef SS_REFRACTION\nsubSurfaceOut.finalRefraction +\n#endif\n#endif\nfinalAmbient +\nfinalDiffuse,\nalpha);\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor=vec4f(finalColor.rgb*lightmapColor.rgb,finalColor.a);\n#else\nfinalColor=vec4f(finalColor.rgb+lightmapColor.rgb,finalColor.a);\n#endif\n#endif\n#endif\nfinalColor=vec4f(finalColor.rgb+finalEmissive,finalColor.a);\n#define CUSTOM_FRAGMENT_BEFORE_FOG\nfinalColor=max(finalColor,vec4f(0.0));\n";Je.IncludesShadersStoreWGSL.logDepthFragment="#ifdef LOGARITHMICDEPTH\nfragmentOutputs.fragDepth=log2(fragmentInputs.vFragmentDepth)*uniforms.logarithmicDepthConstant*0.5;\n#endif\n";Je.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";Je.IncludesShadersStoreWGSL.pbrBlockImageProcessing="#if defined(IMAGEPROCESSINGPOSTPROCESS) || defined(SS_SCATTERING)\n#if !defined(SKIPFINALCOLORCLAMP)\nfinalColor=vec4f(clamp(finalColor.rgb,vec3f(0.),vec3f(30.0)),finalColor.a);\n#endif\n#else\nfinalColor=applyImageProcessing(finalColor);\n#endif\nfinalColor=vec4f(finalColor.rgb,finalColor.a*mesh.visibility);\n#ifdef PREMULTIPLYALPHA\nfinalColor=vec4f(finalColor.rgb*finalColor.a,finalColor.a);;\n#endif\n";Je.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 || fragDepth<furthestDepth) {\n#else\nif (fragDepth<nearestDepth || fragDepth>furthestDepth) {\n#endif\nreturn fragmentOutputs;}\n#ifdef USE_REVERSE_DEPTHBUFFER\nif (fragDepth<nearestDepth && fragDepth>furthestDepth) {\n#else\nif (fragDepth>nearestDepth && fragDepth<furthestDepth) {\n#endif\nfragmentOutputs.depth=vec2f(-fragDepth,fragDepth);return fragmentOutputs;}\n#endif\n";Je.IncludesShadersStoreWGSL.pbrDebug="#if DEBUGMODE>0\nif (input.vClipSpacePosition.x/input.vClipSpacePosition.w>=uniforms.vDebugMode.x) {var color: vec3f;\n#if DEBUGMODE==1\ncolor=fragmentInputs.vPositionW.rgb;\n#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==2 && defined(NORMAL)\ncolor=fragmentInputs.vNormalW.rgb;\n#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==3 && defined(BUMP) || DEBUGMODE==3 && defined(PARALLAX) || DEBUGMODE==3 && defined(ANISOTROPIC)\ncolor=TBN[0];\n#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==4 && defined(BUMP) || DEBUGMODE==4 && defined(PARALLAX) || DEBUGMODE==4 && defined(ANISOTROPIC)\ncolor=TBN[1];\n#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==5\ncolor=normalW;\n#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==6 && defined(MAINUV1)\ncolor= vec3f(input.vMainUV1,0.0);\n#elif DEBUGMODE==7 && defined(MAINUV2)\ncolor= vec3f(input.vMainUV2,0.0);\n#elif DEBUGMODE==8 && defined(CLEARCOAT) && defined(CLEARCOAT_BUMP)\ncolor=clearcoatOut.TBNClearCoat[0];\n#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==9 && defined(CLEARCOAT) && defined(CLEARCOAT_BUMP)\ncolor=clearcoatOut.TBNClearCoat[1];\n#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==10 && defined(CLEARCOAT)\ncolor=clearcoatOut.clearCoatNormalW;\n#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==11 && defined(ANISOTROPIC)\ncolor=anisotropicOut.anisotropicNormal;\n#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==12 && defined(ANISOTROPIC)\ncolor=anisotropicOut.anisotropicTangent;\n#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==13 && defined(ANISOTROPIC)\ncolor=anisotropicOut.anisotropicBitangent;\n#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==20 && defined(ALBEDO)\ncolor=albedoTexture.rgb;\n#ifndef GAMMAALBEDO\n#define DEBUGMODE_GAMMA\n#endif\n#elif DEBUGMODE==21 && defined(AMBIENT)\ncolor=aoOut.ambientOcclusionColorMap.rgb;\n#elif DEBUGMODE==22 && defined(OPACITY)\ncolor=opacityMap.rgb;\n#elif DEBUGMODE==23 && defined(EMISSIVE)\ncolor=emissiveColorTex.rgb;\n#ifndef GAMMAEMISSIVE\n#define DEBUGMODE_GAMMA\n#endif\n#elif DEBUGMODE==24 && defined(LIGHTMAP)\ncolor=lightmapColor;\n#ifndef GAMMALIGHTMAP\n#define DEBUGMODE_GAMMA\n#endif\n#elif DEBUGMODE==25 && defined(REFLECTIVITY) && defined(METALLICWORKFLOW)\ncolor=reflectivityOut.surfaceMetallicColorMap.rgb;\n#elif DEBUGMODE==26 && defined(REFLECTIVITY) && !defined(METALLICWORKFLOW)\ncolor=reflectivityOut.surfaceReflectivityColorMap.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==27 && defined(CLEARCOAT) && defined(CLEARCOAT_TEXTURE)\ncolor= vec3f(clearcoatOut.clearCoatMapData.rg,0.0);\n#elif DEBUGMODE==28 && defined(CLEARCOAT) && defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE)\ncolor=clearcoatOut.clearCoatTintMapData.rgb;\n#elif DEBUGMODE==29 && defined(SHEEN) && defined(SHEEN_TEXTURE)\ncolor=sheenOut.sheenMapData.rgb;\n#elif DEBUGMODE==30 && defined(ANISOTROPIC) && defined(ANISOTROPIC_TEXTURE)\ncolor=anisotropicOut.anisotropyMapData.rgb;\n#elif DEBUGMODE==31 && defined(SUBSURFACE) && defined(SS_THICKNESSANDMASK_TEXTURE)\ncolor=subSurfaceOut.thicknessMap.rgb;\n#elif DEBUGMODE==32 && defined(BUMP)\ncolor=textureSample(bumpSampler,bumpSamplerSampler,fragmentInputs.vBumpUV).rgb;\n#elif DEBUGMODE==40 && defined(SS_REFRACTION)\ncolor=subSurfaceOut.environmentRefraction.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==41 && defined(REFLECTION)\ncolor=reflectionOut.environmentRadiance.rgb;\n#ifndef GAMMAREFLECTION\n#define DEBUGMODE_GAMMA\n#endif\n#elif DEBUGMODE==42 && defined(CLEARCOAT) && defined(REFLECTION)\ncolor=clearcoatOut.environmentClearCoatRadiance.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==50\ncolor=diffuseBase.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==51 && defined(SPECULARTERM)\ncolor=specularBase.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==52 && defined(CLEARCOAT)\ncolor=clearCoatBase.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==53 && defined(SHEEN)\ncolor=sheenBase.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==54 && defined(REFLECTION)\ncolor=reflectionOut.environmentIrradiance.rgb;\n#ifndef GAMMAREFLECTION\n#define DEBUGMODE_GAMMA\n#endif\n#elif DEBUGMODE==60\ncolor=surfaceAlbedo.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==61\ncolor=clearcoatOut.specularEnvironmentR0;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==62 && defined(METALLICWORKFLOW)\ncolor= vec3f(reflectivityOut.metallicRoughness.r);\n#elif DEBUGMODE==71 && defined(METALLICWORKFLOW)\ncolor=reflectivityOut.metallicF0;\n#elif DEBUGMODE==63\ncolor= vec3f(roughness);\n#elif DEBUGMODE==64\ncolor= vec3f(alphaG);\n#elif DEBUGMODE==65\ncolor= vec3f(NdotV);\n#elif DEBUGMODE==66 && defined(CLEARCOAT) && defined(CLEARCOAT_TINT)\ncolor=clearcoatOut.clearCoatColor;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==67 && defined(CLEARCOAT)\ncolor= vec3f(clearcoatOut.clearCoatRoughness);\n#elif DEBUGMODE==68 && defined(CLEARCOAT)\ncolor= vec3f(clearcoatOut.clearCoatNdotV);\n#elif DEBUGMODE==69 && defined(SUBSURFACE) && defined(SS_TRANSLUCENCY)\ncolor=subSurfaceOut.transmittance;\n#elif DEBUGMODE==70 && defined(SUBSURFACE) && defined(SS_REFRACTION)\ncolor=subSurfaceOut.refractionTransmittance;\n#elif DEBUGMODE==72\ncolor= vec3f(microSurface);\n#elif DEBUGMODE==73\ncolor=uniforms.vAlbedoColor.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==74 && !defined(METALLICWORKFLOW)\ncolor=uniforms.vReflectivityColor.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==75\ncolor=uniforms.vEmissiveColor;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==80 && defined(RADIANCEOCCLUSION)\ncolor= vec3f(seo);\n#elif DEBUGMODE==81 && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D)\ncolor= vec3f(eho);\n#elif DEBUGMODE==82 && defined(MS_BRDF_ENERGY_CONSERVATION)\ncolor= vec3f(energyConservationFactor);\n#elif DEBUGMODE==83 && defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\ncolor=specularEnvironmentReflectance;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==84 && defined(CLEARCOAT) && defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\ncolor=clearcoatOut.clearCoatEnvironmentReflectance;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==85 && defined(SHEEN) && defined(REFLECTION)\ncolor=sheenOut.sheenEnvironmentReflectance;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==86 && defined(ALPHABLEND)\ncolor= vec3f(luminanceOverAlpha);\n#elif DEBUGMODE==87\ncolor= vec3f(alpha);\n#elif DEBUGMODE==88 && defined(ALBEDO)\ncolor= vec3f(albedoTexture.a);\n#elif DEBUGMODE==89\ncolor=aoOut.ambientOcclusionColor;\n#else\nvar stripeWidth: f32=30.;var stripePos: f32=abs(floor(input.position.x/stripeWidth));var whichColor: f32=((stripePos)%(2.));var color1: vec3f= vec3f(.6,.2,.2);var color2: vec3f= vec3f(.3,.1,.1);color=mix(color1,color2,whichColor);\n#endif\ncolor*=uniforms.vDebugMode.y;\n#ifdef DEBUGMODE_NORMALIZE\ncolor=normalize(color)*0.5+0.5;\n#endif\n#ifdef DEBUGMODE_GAMMA\ncolor=toGammaSpaceVec3(color);\n#endif\nfragmentOutputs.color=vec4f(color,1.0);\n#ifdef PREPASS\nfragmentOutputs.fragData0=toLinearSpaceVec3(color); \nfragmentOutputs.fragData1=vec4f(0.,0.,0.,0.); \n#endif\n#ifdef DEBUGMODE_FORCERETURN\nreturn fragmentOutputs;\n#endif\n}\n#endif\n";const Fu="pbrPixelShader",wu="#define CUSTOM_FRAGMENT_BEGIN\n#include<prePassDeclaration>[SCENE_MRT_COUNT]\n#include<oitDeclaration>\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE\n#endif\n#include<pbrUboDeclaration>\n#include<pbrFragmentExtraDeclaration>\n#include<lightUboDeclaration>[0..maxSimultaneousLights]\n#include<pbrFragmentSamplersDeclaration>\n#include<imageProcessingDeclaration>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#include<helperFunctions>\n#include<subSurfaceScatteringFunctions>\n#include<importanceSampling>\n#include<pbrHelperFunctions>\n#include<imageProcessingFunctions>\n#include<shadowsFragmentFunctions>\n#include<harmonicsFunctions>\n#include<pbrDirectLightingSetupFunctions>\n#include<pbrDirectLightingFalloffFunctions>\n#include<pbrBRDFFunctions>\n#include<hdrFilteringFunctions>\n#include<pbrDirectLightingFunctions>\n#include<pbrIBLFunctions>\n#include<bumpFragmentMainFunctions>\n#include<bumpFragmentFunctions>\n#ifdef REFLECTION\n#include<reflectionFunction>\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\n#include<pbrBlockAlbedoOpacity>\n#include<pbrBlockReflectivity>\n#include<pbrBlockAmbientOcclusion>\n#include<pbrBlockAlphaFresnel>\n#include<pbrBlockAnisotropic>\n#include<pbrBlockReflection>\n#include<pbrBlockSheen>\n#include<pbrBlockClearcoat>\n#include<pbrBlockIridescence>\n#include<pbrBlockSubSurface>\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\n#include<pbrBlockNormalGeometric>\n#include<bumpFragment>\n#include<pbrBlockNormalFinal>\nvar albedoOpacityOut: albedoOpacityOutParams;\n#ifdef ALBEDO\nvar albedoTexture: vec4f=textureSample(albedoSampler,albedoSamplerSampler,fragmentInputs.vAlbedoUV+uvOffset);\n#endif\n#ifdef OPACITY\nvar opacityMap: vec4f=textureSample(opacitySampler,opacitySamplerSampler,fragmentInputs.vOpacityUV+uvOffset);\n#endif\n#ifdef DECAL\nvar decalColor: vec4f=textureSample(decalSampler,decalSamplerSampler,fragmentInputs.vDecalUV+uvOffset);\n#endif\nalbedoOpacityOut=albedoOpacityBlock(\nuniforms.vAlbedoColor\n#ifdef ALBEDO\n,albedoTexture\n,uniforms.vAlbedoInfos\n#endif\n#ifdef OPACITY\n,opacityMap\n,uniforms.vOpacityInfos\n#endif\n#ifdef DETAIL\n,detailColor\n,uniforms.vDetailInfos\n#endif\n#ifdef DECAL\n,decalColor\n,uniforms.vDecalInfos\n#endif\n);var surfaceAlbedo: vec3f=albedoOpacityOut.surfaceAlbedo;var alpha: f32=albedoOpacityOut.alpha;\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\n#include<depthPrePass>\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\nvar aoOut: ambientOcclusionOutParams;\n#ifdef AMBIENT\nvar ambientOcclusionColorMap: vec3f=textureSample(ambientSampler,ambientSamplerSampler,fragmentInputs.vAmbientUV+uvOffset).rgb;\n#endif\naoOut=ambientOcclusionBlock(\n#ifdef AMBIENT\nambientOcclusionColorMap,\nuniforms.vAmbientInfos\n#endif \n);\n#include<pbrBlockLightmapInit>\n#ifdef UNLIT\nvar diffuseBase: vec3f= vec3f(1.,1.,1.);\n#else\nvar baseColor: vec3f=surfaceAlbedo;var reflectivityOut: reflectivityOutParams;\n#if defined(REFLECTIVITY)\nvar surfaceMetallicOrReflectivityColorMap: vec4f=textureSample(reflectivitySampler,reflectivitySamplerSampler,fragmentInputs.vReflectivityUV+uvOffset);var baseReflectivity: vec4f=surfaceMetallicOrReflectivityColorMap;\n#ifndef METALLICWORKFLOW\n#ifdef REFLECTIVITY_GAMMA\nsurfaceMetallicOrReflectivityColorMap=toLinearSpaceVec4(surfaceMetallicOrReflectivityColorMap);\n#endif\nsurfaceMetallicOrReflectivityColorMap=vec4f(surfaceMetallicOrReflectivityColorMap.rgb*uniforms.vReflectivityInfos.y,surfaceMetallicOrReflectivityColorMap.a);\n#endif\n#endif\n#if defined(MICROSURFACEMAP)\nvar microSurfaceTexel: vec4f=textureSample(microSurfaceSampler,microSurfaceSamplerSampler,fragmentInputs.vMicroSurfaceSamplerUV+uvOffset)*uniforms.vMicroSurfaceSamplerInfos.y;\n#endif\n#ifdef METALLICWORKFLOW\nvar metallicReflectanceFactors: vec4f=uniforms.vMetallicReflectanceFactors;\n#ifdef REFLECTANCE\nvar reflectanceFactorsMap: vec4f=textureSample(reflectanceSampler,reflectanceSamplerSampler,fragmentInputs.vReflectanceUV+uvOffset);\n#ifdef REFLECTANCE_GAMMA\nreflectanceFactorsMap=toLinearSpaceVec4(reflectanceFactorsMap);\n#endif\nmetallicReflectanceFactors=vec4f(metallicReflectanceFactors.rgb*reflectanceFactorsMap.rgb,metallicReflectanceFactors.a);\n#endif\n#ifdef METALLIC_REFLECTANCE\nvar metallicReflectanceFactorsMap: vec4f=textureSample(metallicReflectanceSampler,metallicReflectanceSamplerSampler,fragmentInputs.vMetallicReflectanceUV+uvOffset);\n#ifdef METALLIC_REFLECTANCE_GAMMA\nmetallicReflectanceFactorsMap=toLinearSpaceVec4(metallicReflectanceFactorsMap);\n#endif\n#ifndef METALLIC_REFLECTANCE_USE_ALPHA_ONLY\nmetallicReflectanceFactors=vec4f(metallicReflectanceFactors.rgb*reflectanceFactorsMap.rgb,metallicReflectanceFactors.a);\n#endif\nmetallicReflectanceFactors*=metallicReflectanceFactorsMap.a;\n#endif\n#endif\nreflectivityOut=reflectivityBlock(\nuniforms.vReflectivityColor\n#ifdef METALLICWORKFLOW\n,surfaceAlbedo\n,metallicReflectanceFactors\n#endif\n#ifdef REFLECTIVITY\n,uniforms.vReflectivityInfos\n,surfaceMetallicOrReflectivityColorMap\n#endif\n#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)\n,aoOut.ambientOcclusionColor\n#endif\n#ifdef MICROSURFACEMAP\n,microSurfaceTexel\n#endif\n#ifdef DETAIL\n,detailColor\n,uniforms.vDetailInfos\n#endif\n);var microSurface: f32=reflectivityOut.microSurface;var roughness: f32=reflectivityOut.roughness;\n#ifdef METALLICWORKFLOW\nsurfaceAlbedo=reflectivityOut.surfaceAlbedo;\n#endif\n#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)\naoOut.ambientOcclusionColor=reflectivityOut.ambientOcclusionColor;\n#endif\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\nvar alphaFresnelOut: alphaFresnelOutParams;alphaFresnelOut=alphaFresnelBlock(\nnormalW,\nviewDirectionW,\nalpha,\nmicroSurface\n);alpha=alphaFresnelOut.alpha;\n#endif\n#endif\n#include<pbrBlockGeometryInfo>\n#ifdef ANISOTROPIC\nvar anisotropicOut: anisotropicOutParams;\n#ifdef ANISOTROPIC_TEXTURE\nvar anisotropyMapData: vec3f=textureSample(anisotropySampler,anisotropySamplerSampler,fragmentInputs.vAnisotropyUV+uvOffset).rgb*uniforms.vAnisotropyInfos.y;\n#endif\nanisotropicOut=anisotropicBlock(\nuniforms.vAnisotropy,\nroughness,\n#ifdef ANISOTROPIC_TEXTURE\nanisotropyMapData,\n#endif\nTBN,\nnormalW,\nviewDirectionW \n);\n#endif\n#ifdef REFLECTION\nvar reflectionOut: reflectionOutParams;\n#ifndef USE_CUSTOM_REFLECTION\nreflectionOut=reflectionBlock(\ninput.vPositionW\n,normalW\n,alphaG\n,uniforms.vReflectionMicrosurfaceInfos\n,uniforms.vReflectionInfos\n,uniforms.vReflectionColor\n#ifdef ANISOTROPIC\n,anisotropicOut\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\n,NdotVUnclamped\n#endif\n#ifdef LINEARSPECULARREFLECTION\n,roughness\n#endif\n,reflectionSampler\n,reflectionSamplerSampler\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\n,input.vEnvironmentIrradiance\n#endif\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)\n,uniforms.reflectionMatrix\n#endif\n#endif\n#ifdef USEIRRADIANCEMAP\n,irradianceSampler\n,irradianceSamplerSampler\n#endif\n#ifndef LODBASEDMICROSFURACE\n,reflectionLowSampler\n,reflectionLowSamplerSampler\n,reflectionHighSampler\n,reflectionHighSamplerSampler\n#endif\n#ifdef REALTIME_FILTERING\n,uniforms.vReflectionFilteringInfo\n#endif\n);\n#else\n#define CUSTOM_REFLECTION\n#endif\n#endif\n#include<pbrBlockReflectance0>\n#ifdef SHEEN\nvar sheenOut: sheenOutParams;\n#ifdef SHEEN_TEXTURE\nvar sheenMapData: vec4f=textureSample(sheenSampler,sheenSamplerSampler,fragmentInputs.vSheenUV+uvOffset);\n#endif\n#if defined(SHEEN_ROUGHNESS) && defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE)\nvar sheenMapRoughnessData: vec4f=textureSample(sheenRoughnessSampler,sheenRoughnessSamplerSampler,fragmentInputs.vSheenRoughnessUV+uvOffset)*uniforms.vSheenInfos.w;\n#endif\nsheenOut=sheenBlock(\nuniforms.vSheenColor\n#ifdef SHEEN_ROUGHNESS\n,uniforms.vSheenRoughness\n#if defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE)\n,sheenMapRoughnessData\n#endif\n#endif\n,roughness\n#ifdef SHEEN_TEXTURE\n,sheenMapData\n,uniforms.vSheenInfos.y\n#endif\n,reflectance\n#ifdef SHEEN_LINKWITHALBEDO\n,baseColor\n,surfaceAlbedo\n#endif\n#ifdef ENVIRONMENTBRDF\n,NdotV\n,environmentBrdf\n#endif\n#if defined(REFLECTION) && defined(ENVIRONMENTBRDF)\n,AARoughnessFactors\n,uniforms.vReflectionMicrosurfaceInfos\n,uniforms.vReflectionInfos\n,uniforms.vReflectionColor\n,uniforms.vLightingIntensity\n,reflectionSampler\n,reflectionSamplerSampler\n,reflectionOut.reflectionCoords\n,NdotVUnclamped\n#ifndef LODBASEDMICROSFURACE\n,reflectionLowSampler\n,reflectionLowSamplerSampler\n,reflectionHighSampler\n,reflectionHighSamplerSampler\n#endif\n#ifdef REALTIME_FILTERING\n,vReflectionFilteringInfo\n#endif\n#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION)\n,seo\n#endif\n#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D)\n,eho\n#endif\n#endif\n);\n#ifdef SHEEN_LINKWITHALBEDO\nsurfaceAlbedo=sheenOut.surfaceAlbedo;\n#endif\n#endif\n#ifdef CLEARCOAT\n#ifdef CLEARCOAT_TEXTURE\nvar clearCoatMapData: vec2f=textureSample(clearCoatSampler,clearCoatSamplerSampler,fragmentInputs.vClearCoatUV+uvOffset).rg*uniforms.vClearCoatInfos.y;\n#endif\n#endif\n#ifdef IRIDESCENCE\nvar iridescenceOut: iridescenceOutParams;\n#ifdef IRIDESCENCE_TEXTURE\nvar iridescenceMapData: vec2f=textureSample(iridescenceSampler,iridescenceSamplerSampler,fragmentInputs.vIridescenceUV+uvOffset).rg*vIridescenceInfos.y;\n#endif\n#ifdef IRIDESCENCE_THICKNESS_TEXTURE\nvar iridescenceThicknessMapData: vec2f=textureSample(iridescenceThicknessSampler,iridescenceThicknessSamplerSampler,fragmentInputs.vIridescenceThicknessUV+uvOffset).rg*vIridescenceInfos.w;\n#endif\niridescenceOut=iridescenceBlock(\nuniforms.vIridescenceParams\n,NdotV\n,specularEnvironmentR0\n#ifdef IRIDESCENCE_TEXTURE\n,iridescenceMapData\n#endif\n#ifdef IRIDESCENCE_THICKNESS_TEXTURE\n,iridescenceThicknessMapData\n#endif\n#ifdef CLEARCOAT\n,NdotVUnclamped\n#ifdef CLEARCOAT_TEXTURE\n,clearCoatMapData\n#endif\n#endif\n);var iridescenceIntensity: f32=iridescenceOut.iridescenceIntensity;specularEnvironmentR0=iridescenceOut.specularEnvironmentR0;\n#endif\nvar clearcoatOut: clearcoatOutParams;\n#ifdef CLEARCOAT\n#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE)\nvar clearCoatMapRoughnessData: vec4f=textureSample(clearCoatRoughnessSampler,clearCoatRoughnessSamplerSampler,fragmentInputs.vClearCoatRoughnessUV+uvOffset)*uniforms.vClearCoatInfos.w;\n#endif\n#if defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE)\nvar clearCoatTintMapData: vec4f=textureSample(clearCoatTintSampler,clearCoatTintSamplerSampler,fragmentInputs.vClearCoatTintUV+uvOffset);\n#endif\n#ifdef CLEARCOAT_BUMP\nvar clearCoatBumpMapData: vec4f=textureSample(clearCoatBumpSampler,clearCoatBumpSamplerSampler,fragmentInputs.vClearCoatBumpUV+uvOffset);\n#endif\nclearcoatOut=clearcoatBlock(\ninput.vPositionW\n,geometricNormalW\n,viewDirectionW\n,uniforms.vClearCoatParams\n#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE)\n,clearCoatMapRoughnessData\n#endif\n,specularEnvironmentR0\n#ifdef CLEARCOAT_TEXTURE\n,clearCoatMapData\n#endif\n#ifdef CLEARCOAT_TINT\n,uniforms.vClearCoatTintParams\n,uniforms.clearCoatColorAtDistance\n,uniforms.vClearCoatRefractionParams\n#ifdef CLEARCOAT_TINT_TEXTURE\n,clearCoatTintMapData\n#endif\n#endif\n#ifdef CLEARCOAT_BUMP\n,uniforms.vClearCoatBumpInfos\n,clearCoatBumpMapData\n,fragmentInputs.vClearCoatBumpUV\n#if defined(TANGENT) && defined(NORMAL)\n,vTBN\n#else\n,uniforms.vClearCoatTangentSpaceParams\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\n,uniforms.normalMatrix\n#endif\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\n,faceNormal\n#endif\n#ifdef REFLECTION\n,uniforms.vReflectionMicrosurfaceInfos\n,uniforms.vReflectionInfos\n,uniforms.vReflectionColor\n,uniforms.vLightingIntensity\n,reflectionSampler\n,reflectionSamplerSampler\n#ifndef LODBASEDMICROSFURACE\n,reflectionLowSampler\n,reflectionLowSamplerSampler\n,reflectionHighSampler\n,reflectionHighSamplerSampler\n#endif\n#ifdef REALTIME_FILTERING\n,uniforms.vReflectionFilteringInfo\n#endif\n#endif\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n#ifdef RADIANCEOCCLUSION\n,ambientMonochrome\n#endif\n#endif\n#if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING)\n,select(-1.,1.,fragmentInputs.frontFacing)\n#endif\n);\n#else\nclearcoatOut.specularEnvironmentR0=specularEnvironmentR0;\n#endif\n#include<pbrBlockReflectance>\nvar subSurfaceOut: subSurfaceOutParams;\n#ifdef SUBSURFACE\n#ifdef SS_THICKNESSANDMASK_TEXTURE\nvar thicknessMap: vec4f=textureSample(thicknessSampler,thicknessSamplerSampler,fragmentInputs.vThicknessUV+uvOffset);\n#endif\n#ifdef SS_REFRACTIONINTENSITY_TEXTURE\nvar refractionIntensityMap: vec4f=textureSample(refractionIntensitySampler,refractionIntensitySamplerSampler,fragmentInputs.vRefractionIntensityUV+uvOffset);\n#endif\n#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE\nvar translucencyIntensityMap: vec4f=textureSample(translucencyIntensitySampler,translucencyIntensitySamplerSampler,fragmentInputs.vTranslucencyIntensityUV+uvOffset);\n#endif\n#ifdef SS_TRANSLUCENCYCOLOR_TEXTURE\nvar translucencyColorMap: vec4f=textureSample(translucencyColorSampler,translucencyColorSamplerSampler,fragmentInputs.vTranslucencyColorUV+uvOffset);\n#endif\nsubSurfaceOut=subSurfaceBlock(\nuniforms.vSubSurfaceIntensity\n,uniforms.vThicknessParam\n,uniforms.vTintColor\n,normalW\n,specularEnvironmentReflectance\n#ifdef SS_THICKNESSANDMASK_TEXTURE\n,thicknessMap\n#endif\n#ifdef SS_REFRACTIONINTENSITY_TEXTURE\n,refractionIntensityMap\n#endif\n#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE\n,translucencyIntensityMap\n#endif\n#ifdef REFLECTION\n#ifdef SS_TRANSLUCENCY\n,uniforms.reflectionMatrix\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)\n,reflectionOut.irradianceVector\n#endif\n#if defined(REALTIME_FILTERING)\n,reflectionSampler\n,reflectionSamplerSampler\n,vReflectionFilteringInfo\n#endif\n#endif\n#ifdef USEIRRADIANCEMAP\n,irradianceSampler\n,irradianceSamplerSampler\n#endif\n#endif\n#endif\n#if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY)\n,surfaceAlbedo\n#endif\n#ifdef SS_REFRACTION\n,input.vPositionW\n,viewDirectionW\n,scene.view\n,uniforms.vRefractionInfos\n,uniforms.refractionMatrix\n,uniforms.vRefractionMicrosurfaceInfos\n,uniforms.vLightingIntensity\n#ifdef SS_LINKREFRACTIONTOTRANSPARENCY\n,alpha\n#endif\n#ifdef SS_LODINREFRACTIONALPHA\n,NdotVUnclamped\n#endif\n#ifdef SS_LINEARSPECULARREFRACTION\n,roughness\n#endif\n,alphaG\n,refractionSampler\n,refractionSamplerSampler\n#ifndef LODBASEDMICROSFURACE\n,refractionLowSampler\n,refractionLowSamplerSampler\n,refractionHighSampler\n,refractionHighSamplerSampler\n#endif\n#ifdef ANISOTROPIC\n,anisotropicOut\n#endif\n#ifdef REALTIME_FILTERING\n,uniforms.vRefractionFilteringInfo\n#endif\n#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC\n,uniforms.vRefractionPosition\n,uniforms.vRefractionSize\n#endif\n#ifdef SS_DISPERSION\n,dispersion\n#endif\n#endif\n#ifdef SS_TRANSLUCENCY\n,uniforms.vDiffusionDistance\n,uniforms.vTranslucencyColor\n#ifdef SS_TRANSLUCENCYCOLOR_TEXTURE\n,translucencyColorMap\n#endif\n#endif\n);\n#ifdef SS_REFRACTION\nsurfaceAlbedo=subSurfaceOut.surfaceAlbedo;\n#ifdef SS_LINKREFRACTIONTOTRANSPARENCY\nalpha=subSurfaceOut.alpha;\n#endif\n#endif\n#else\nsubSurfaceOut.specularEnvironmentReflectance=specularEnvironmentReflectance;\n#endif\n#include<pbrBlockDirectLighting>\n#include<lightFragment>[0..maxSimultaneousLights]\n#include<pbrBlockFinalLitComponents>\n#endif \n#include<pbrBlockFinalUnlitComponents>\n#define CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION\n#include<pbrBlockFinalColorComposition>\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#include<pbrBlockImageProcessing>\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\n#ifdef PREPASS\nvar writeGeometryInfo: f32=select(0.0,1.0,finalColor.a>0.4);var fragData: array<vec4<f32>,SCENE_MRT_COUNT>;\n#ifdef PREPASS_POSITION\nfragData[PREPASS_POSITION_INDEX]= vec4f(input.vPositionW,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#endif\n#ifdef PREPASS_ALBEDO_SQRT\nvar sqAlbedo: vec3f=sqrt(surfaceAlbedo); \n#endif\n#ifdef PREPASS_IRRADIANCE\nvar irradiance: vec3f=finalDiffuse;\n#ifndef UNLIT\n#ifdef REFLECTION\nirradiance+=finalIrradiance;\n#endif\n#endif\n#ifdef SS_SCATTERING\nfragData[0]= vec4f(finalColor.rgb-irradiance,finalColor.a); \nirradiance/=sqAlbedo;\n#else\nfragData[0]=finalColor; \nvar scatteringDiffusionProfile: f32=255.;\n#endif\nfragData[PREPASS_IRRADIANCE_INDEX]= vec4f(clamp(irradiance, vec3f(0.), vec3f(1.)),writeGeometryInfo*scatteringDiffusionProfile/255.); \n#else\nfragData[0]= vec4f(finalColor.rgb,finalColor.a);\n#endif\n#ifdef PREPASS_DEPTH\nfragData[PREPASS_DEPTH_INDEX]= vec4f(fragmentInputs.vViewPos.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_ALBEDO_SQRT\nfragData[PREPASS_ALBEDO_SQRT_INDEX]= vec4f(sqAlbedo,writeGeometryInfo); \n#endif\n#ifdef PREPASS_REFLECTIVITY\n#ifndef UNLIT\nfragData[PREPASS_REFLECTIVITY_INDEX]= vec4f(specularEnvironmentR0,microSurface)*writeGeometryInfo;\n#else\nfragData[PREPASS_REFLECTIVITY_INDEX]= vec4f( 0.0,0.0,0.0,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=finalColor;\n#endif\n#include<oitFragment>\n#if ORDER_INDEPENDENT_TRANSPARENCY\nif (fragDepth==nearestDepth) {fragmentOutputs.frontColor=vec4f(fragmentOutputs.frontColor.rgb+finalColor.rgb*finalColor.a*alphaMultiplier,1.0-alphaMultiplier*(1.0-finalColor.a));} else {fragmentOutputs.backColor+=finalColor;}\n#endif\n#include<pbrDebug>\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";Je.ShadersStoreWGSL[Fu]=wu;const Uu={name:Fu,shader:wu};var Bu=Object.freeze({__proto__:null,pbrPixelShaderWGSL:Uu});Je.IncludesShadersStore.decalVertexDeclaration="#ifdef DECAL\nuniform vec4 vDecalInfos;uniform mat4 decalMatrix;\n#endif\n";Je.IncludesShadersStore.pbrVertexDeclaration="uniform mat4 view;uniform mat4 viewProjection;\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<decalVertexDeclaration>\n#define ADDITIONAL_VERTEX_DECLARATION\n";Je.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";Je.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";Je.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<sceneUboDeclaration>\n#include<meshUboDeclaration>\n";Je.IncludesShadersStore.uvAttributeDeclaration="#ifdef UV{X}\nattribute vec2 uv{X};\n#endif\n";Je.IncludesShadersStore.mainUVVaryingDeclaration="#ifdef MAINUV{X}\nvarying vec2 vMainUV{X};\n#endif\n";Je.IncludesShadersStore.bonesDeclaration="#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";Je.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";Je.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)\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)\nuniform mat4 previousWorld;\n#endif\n#endif\n";Je.IncludesShadersStore.prePassVertexDeclaration="#ifdef PREPASS\n#ifdef PREPASS_DEPTH\nvarying vec3 vViewPos;\n#endif\n#ifdef PREPASS_VELOCITY\nuniform mat4 previousViewProjection;varying vec4 vCurrentPosition;varying vec4 vPreviousPosition;\n#endif\n#endif\n";Je.IncludesShadersStore.samplerVertexDeclaration="#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0\nvarying vec2 v_VARYINGNAME_UV;\n#endif\n";Je.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";Je.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";Je.IncludesShadersStore.clipPlaneVertexDeclaration="#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";Je.IncludesShadersStore.fogVertexDeclaration="#ifdef FOG\nvarying vec3 vFogDistance;\n#endif\n";Je.IncludesShadersStore.lightVxFragmentDeclaration="#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";Je.IncludesShadersStore.lightVxUboDeclaration="#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";Je.IncludesShadersStore.morphTargetsVertexGlobalDeclaration="#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";Je.IncludesShadersStore.morphTargetsVertexDeclaration="#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";Je.IncludesShadersStore.logDepthDeclaration="#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;varying float vFragmentDepth;\n#endif\n";Je.IncludesShadersStore.morphTargetsVertexGlobal="#ifdef MORPHTARGETS\n#ifdef MORPHTARGETS_TEXTURE\nfloat vertexID;\n#endif\n#endif\n";Je.IncludesShadersStore.morphTargetsVertex="#ifdef MORPHTARGETS\n#ifdef MORPHTARGETS_TEXTURE\n#if {X}==0\nfor (int i=0; i<NUM_MORPH_INFLUENCERS; i++) {if (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";Je.IncludesShadersStore.instancesVertex="#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#if defined(PREPASS_VELOCITY) || defined(VELOCITY)\nmat4 finalPreviousWorld=mat4(previousWorld0,previousWorld1,previousWorld2,previousWorld3);\n#endif\n#ifdef THIN_INSTANCES\nfinalWorld=world*finalWorld;\n#if defined(PREPASS_VELOCITY) || defined(VELOCITY)\nfinalPreviousWorld=previousWorld*finalPreviousWorld;\n#endif\n#endif\n#else\nmat4 finalWorld=world;\n#if defined(PREPASS_VELOCITY) || defined(VELOCITY)\nmat4 finalPreviousWorld=previousWorld;\n#endif\n#endif\n";Je.IncludesShadersStore.bonesVertex="#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";Je.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";Je.IncludesShadersStore.prePassVertex="#ifdef PREPASS_DEPTH\nvViewPos=(view*worldPos).rgb;\n#endif\n#if defined(PREPASS_VELOCITY) && 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";Je.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";Je.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";Je.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";Je.IncludesShadersStore.clipPlaneVertex="#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";Je.IncludesShadersStore.fogVertex="#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif\n";Je.IncludesShadersStore.shadowsVertex="#ifdef SHADOWS\n#if defined(SHADOWCSM{X})\nvPositionFromCamera{X}=view*worldPos;for (int i=0; i<SHADOWCSMNUM_CASCADES{X}; i++) {vPositionFromLight{X}[i]=lightMatrix{X}[i]*worldPos;\n#ifdef USE_REVERSE_DEPTHBUFFER\nvDepthMetric{X}[i]=(-vPositionFromLight{X}[i].z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#else\nvDepthMetric{X}[i]=(vPositionFromLight{X}[i].z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#endif\n}\n#elif defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\n#ifdef USE_REVERSE_DEPTHBUFFER\nvDepthMetric{X}=(-vPositionFromLight{X}.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#else\nvDepthMetric{X}=(vPositionFromLight{X}.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#endif\n#endif\n#endif\n";Je.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";Je.IncludesShadersStore.logDepthVertex="#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;gl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif\n";const Gu="pbrVertexShader",Vu="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<uvAttributeDeclaration>[2..7]\n#include<mainUVVaryingDeclaration>[1..7]\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n#include<bakedVertexAnimationDeclaration>\n#include<instancesDeclaration>\n#include<prePassVertexDeclaration>\n#include<samplerVertexDeclaration>(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo)\n#include<samplerVertexDeclaration>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail)\n#include<samplerVertexDeclaration>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient)\n#include<samplerVertexDeclaration>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity)\n#include<samplerVertexDeclaration>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive)\n#include<samplerVertexDeclaration>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap)\n#include<samplerVertexDeclaration>(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity)\n#include<samplerVertexDeclaration>(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler)\n#include<samplerVertexDeclaration>(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance)\n#include<samplerVertexDeclaration>(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance)\n#include<samplerVertexDeclaration>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump)\n#include<samplerVertexDeclaration>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal)\n#ifdef CLEARCOAT\n#include<samplerVertexDeclaration>(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat)\n#include<samplerVertexDeclaration>(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness)\n#include<samplerVertexDeclaration>(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump)\n#include<samplerVertexDeclaration>(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint)\n#endif\n#ifdef IRIDESCENCE\n#include<samplerVertexDeclaration>(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence)\n#include<samplerVertexDeclaration>(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness)\n#endif\n#ifdef SHEEN\n#include<samplerVertexDeclaration>(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen)\n#include<samplerVertexDeclaration>(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness)\n#endif\n#ifdef ANISOTROPIC\n#include<samplerVertexDeclaration>(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy)\n#endif\n#ifdef SUBSURFACE\n#include<samplerVertexDeclaration>(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness)\n#include<samplerVertexDeclaration>(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity)\n#include<samplerVertexDeclaration>(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity)\n#include<samplerVertexDeclaration>(_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<harmonicsFunctions>\n#endif\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightVxFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[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<logDepthDeclaration>\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<morphTargetsVertexGlobal>\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif\n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#if defined(PREPASS) && defined(PREPASS_VELOCITY) && !defined(BONES_VELOCITY_ENABLED)\nvCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0);\n#endif\n#include<bonesVertex>\n#include<bakedVertexAnimation>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);vPositionW=vec3(worldPos);\n#include<prePassVertex>\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<uvVariableDeclaration>[2..7]\n#include<samplerVertexImplementation>(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_MATRIXNAME_,albedo,_INFONAME_,AlbedoInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_MATRIXNAME_,detail,_INFONAME_,DetailInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_MATRIXNAME_,ambient,_INFONAME_,AmbientInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_MATRIXNAME_,opacity,_INFONAME_,OpacityInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_MATRIXNAME_,emissive,_INFONAME_,EmissiveInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_MATRIXNAME_,lightmap,_INFONAME_,LightmapInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_MATRIXNAME_,reflectivity,_INFONAME_,ReflectivityInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_MATRIXNAME_,microSurfaceSampler,_INFONAME_,MicroSurfaceSamplerInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_MATRIXNAME_,metallicReflectance,_INFONAME_,MetallicReflectanceInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_MATRIXNAME_,reflectance,_INFONAME_,ReflectanceInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_MATRIXNAME_,bump,_INFONAME_,BumpInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_MATRIXNAME_,decal,_INFONAME_,DecalInfos.x)\n#ifdef CLEARCOAT\n#include<samplerVertexImplementation>(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_MATRIXNAME_,clearCoat,_INFONAME_,ClearCoatInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness,_MATRIXNAME_,clearCoatRoughness,_INFONAME_,ClearCoatInfos.z)\n#include<samplerVertexImplementation>(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_MATRIXNAME_,clearCoatBump,_INFONAME_,ClearCoatBumpInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_MATRIXNAME_,clearCoatTint,_INFONAME_,ClearCoatTintInfos.x)\n#endif\n#ifdef IRIDESCENCE\n#include<samplerVertexImplementation>(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence,_MATRIXNAME_,iridescence,_INFONAME_,IridescenceInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness,_MATRIXNAME_,iridescenceThickness,_INFONAME_,IridescenceInfos.z)\n#endif\n#ifdef SHEEN\n#include<samplerVertexImplementation>(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_MATRIXNAME_,sheen,_INFONAME_,SheenInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness,_MATRIXNAME_,sheenRoughness,_INFONAME_,SheenInfos.z)\n#endif\n#ifdef ANISOTROPIC\n#include<samplerVertexImplementation>(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_MATRIXNAME_,anisotropy,_INFONAME_,AnisotropyInfos.x)\n#endif\n#ifdef SUBSURFACE\n#include<samplerVertexImplementation>(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_MATRIXNAME_,thickness,_INFONAME_,ThicknessInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_MATRIXNAME_,refractionIntensity,_INFONAME_,RefractionIntensityInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_MATRIXNAME_,translucencyIntensity,_INFONAME_,TranslucencyIntensityInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,SS_TRANSLUCENCYCOLOR_TEXTURE,_VARYINGNAME_,TranslucencyColor,_MATRIXNAME_,translucencyColor,_INFONAME_,TranslucencyColorInfos.x)\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#include<vertexColorMixing>\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}";Je.ShadersStore[Gu]=Vu;const ku={name:Gu,shader:Vu};var Xu=Object.freeze({__proto__:null,pbrVertexShader:ku});Je.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_DEPTH\nvarying highp vec3 vViewPos;\n#endif\n#ifdef PREPASS_VELOCITY\nvarying highp vec4 vCurrentPosition;varying highp vec4 vPreviousPosition;\n#endif\n#endif\n";Je.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";Je.IncludesShadersStore.decalFragmentDeclaration="#ifdef DECAL\nuniform vec4 vDecalInfos;\n#endif\n";Je.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<decalFragmentDeclaration>\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";Je.IncludesShadersStore.pbrFragmentExtraDeclaration="varying vec3 vPositionW;\n#if DEBUGMODE>0\nvarying vec4 vClipSpacePosition;\n#endif\n#include<mainUVVaryingDeclaration>[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";Je.IncludesShadersStore.lightFragmentDeclaration="#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";Je.IncludesShadersStore.lightUboDeclaration="#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";Je.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";Je.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";Je.IncludesShadersStore.pbrFragmentSamplersDeclaration="#include<samplerFragmentDeclaration>(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_SAMPLERNAME_,albedo)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_SAMPLERNAME_,reflectivity)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_SAMPLERNAME_,microSurface)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_SAMPLERNAME_,metallicReflectance)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_SAMPLERNAME_,reflectance)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_SAMPLERNAME_,decal)\n#ifdef CLEARCOAT\n#include<samplerFragmentDeclaration>(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_SAMPLERNAME_,clearCoat)\n#include<samplerFragmentAlternateDeclaration>(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness)\n#if defined(CLEARCOAT_TEXTURE_ROUGHNESS)\nuniform sampler2D clearCoatRoughnessSampler;\n#endif\n#include<samplerFragmentDeclaration>(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_SAMPLERNAME_,clearCoatBump)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_SAMPLERNAME_,clearCoatTint)\n#endif\n#ifdef IRIDESCENCE\n#include<samplerFragmentDeclaration>(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence,_SAMPLERNAME_,iridescence)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness,_SAMPLERNAME_,iridescenceThickness)\n#endif\n#ifdef SHEEN\n#include<samplerFragmentDeclaration>(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_SAMPLERNAME_,sheen)\n#include<samplerFragmentAlternateDeclaration>(_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<samplerFragmentDeclaration>(_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<samplerFragmentDeclaration>(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_SAMPLERNAME_,thickness)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_SAMPLERNAME_,refractionIntensity)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_SAMPLERNAME_,translucencyIntensity)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,SS_TRANSLUCENCYCOLOR_TEXTURE,_VARYINGNAME_,TranslucencyColor,_SAMPLERNAME_,translucencyColor)\n#endif\n";Je.IncludesShadersStore.imageProcessingDeclaration="#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";Je.IncludesShadersStore.clipPlaneFragmentDeclaration="#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";Je.IncludesShadersStore.fogFragmentDeclaration="#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";Je.IncludesShadersStore.subSurfaceScatteringFunctions="bool testLightingForSSS(float diffusionProfile)\n{return diffusionProfile<1.;}";Je.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);}";Je.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=anisotropy>=0.0 ? B : T;vec3 anisotropicFrameTangent=cross(normalize(anisotropicFrameDirection),V);vec3 anisotropicFrameNormal=cross(anisotropicFrameTangent,anisotropicFrameDirection);vec3 anisotropicNormal=normalize(mix(N,anisotropicFrameNormal,abs(anisotropy)));return anisotropicNormal;}\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";Je.IncludesShadersStore.imageProcessingFunctions="#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<PBRNeutralStartCompression) return color;float d=1.-PBRNeutralStartCompression;float newPeak=1.-d*d/(peak+d-PBRNeutralStartCompression);color*=newPeak/peak;float g=1.-1./(PBRNeutralDesaturation*(peak-newPeak)+1.);return mix(color,newPeak*vec3(1,1,1),g);}\n#endif\n#if TONEMAPPING==2\nconst mat3 ACESInputMat=mat3(\nvec3(0.59719,0.07600,0.02840),\nvec3(0.35458,0.90834,0.13383),\nvec3(0.04823,0.01566,0.83777)\n);const mat3 ACESOutputMat=mat3(\nvec3( 1.60475,-0.10208,-0.00327),\nvec3(-0.53108, 1.10813,-0.07276),\nvec3(-0.07367,-0.00605, 1.07602)\n);vec3 RRTAndODTFit(vec3 v)\n{vec3 a=v*(v+0.0245786)-0.000090537;vec3 b=v*(0.983729*v+0.4329510)+0.238081;return a/b;}\nvec3 ACESFitted(vec3 color)\n{color=ACESInputMat*color;color=RRTAndODTFit(color);color=ACESOutputMat*color;color=saturate(color);return color;}\n#endif\n#define CUSTOM_IMAGEPROCESSINGFUNCTIONS_DEFINITIONS\nvec4 applyImageProcessing(vec4 result) {\n#define CUSTOM_IMAGEPROCESSINGFUNCTIONS_UPDATERESULT_ATSTART\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;viewportXY=viewportXY*2.0-1.0;vec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);float vignetteTerm=dot(vignetteXY1,vignetteXY1);float vignette=pow(vignetteTerm,vignetteSettings2.w);vec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);result.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#if TONEMAPPING==3\nresult.rgb=PBRNeutralToneMapping(result.rgb);\n#elif TONEMAPPING==2\nresult.rgb=ACESFitted(result.rgb);\n#elif TONEMAPPING==1\nconst float tonemappingCalibration=1.590579;result.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\nresult.rgb=toGammaSpace(result.rgb);result.rgb=saturate(result.rgb);\n#ifdef CONTRAST\nvec3 resultHighContrast=result.rgb*result.rgb*(3.0-2.0*result.rgb);if (contrast<1.0) {result.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);} else {result.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);}\n#endif\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\nfloat luma=getLuminance(result.rgb);vec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));vec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;result.rgb*=colorCurve.rgb;result.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\n#ifdef DITHER\nfloat rand=getRand(gl_FragCoord.xy*vInverseScreenSize);float dither=mix(-ditherIntensity,ditherIntensity,rand);result.rgb=saturate(result.rgb+vec3(dither));\n#endif\n#define CUSTOM_IMAGEPROCESSINGFUNCTIONS_UPDATERESULT_ATEND\nreturn result;}";Je.IncludesShadersStore.shadowsFragmentFunctions="#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))<depth) visibility-=0.25;if (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;if (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;if (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;if (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;if (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;if (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);}\n#define inline\nfloat computeShadowWithESMCube(vec3 worldPos,vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{vec3 directionToLight=worldPos-lightPosition;float depth=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);float shadowPixelDepth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);return esm;}\n#define inline\nfloat computeShadowWithCloseESMCube(vec3 worldPos,vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{vec3 directionToLight=worldPos-lightPosition;float depth=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);float shadowPixelDepth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);return esm;}\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define inline\nfloat computeShadowCSM(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray shadowSampler,float darkness,float frustumEdgeFalloff)\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);vec3 uvLayer=vec3(uv.x,uv.y,layer);float shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uvLayer));\n#else\nfloat shadow=texture2D(shadowSampler,uvLayer).x;\n#endif\nreturn shadowPixelDepth>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.))<shadowPixelDepth) visibility-=0.25;if (unpack(TEXTUREFUNC(shadowSampler,uv+poissonDisk[1]*mapSize,0.))<shadowPixelDepth) visibility-=0.25;if (unpack(TEXTUREFUNC(shadowSampler,uv+poissonDisk[2]*mapSize,0.))<shadowPixelDepth) visibility-=0.25;if (unpack(TEXTUREFUNC(shadowSampler,uv+poissonDisk[3]*mapSize,0.))<shadowPixelDepth) visibility-=0.25;\n#else\nif (TEXTUREFUNC(shadowSampler,uv+poissonDisk[0]*mapSize,0.).x<shadowPixelDepth) visibility-=0.25;if (TEXTUREFUNC(shadowSampler,uv+poissonDisk[1]*mapSize,0.).x<shadowPixelDepth) visibility-=0.25;if (TEXTUREFUNC(shadowSampler,uv+poissonDisk[2]*mapSize,0.).x<shadowPixelDepth) visibility-=0.25;if (TEXTUREFUNC(shadowSampler,uv+poissonDisk[3]*mapSize,0.).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);}}\n#define inline\nfloat computeShadowWithESM(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=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; i<searchTapCount; i ++) {blockerDepth=texture2D(depthSampler,vec3(uvDepth.xy+(lightSizeUV*lightSizeUVCorrection*shadowMapSizeInverse*PoissonSamplers32[i].xy),layer)).r;if (blockerDepth<depthMetric) {sumBlockerDepth+=blockerDepth;numBlocker++;}}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;float AAOffset=shadowMapSizeInverse*10.;float penumbraRatio=((depthMetric-avgBlockerDepth)*depthCorrection+AAOffset);vec4 filterRadius=vec4(penumbraRatio*lightSizeUV*lightSizeUVCorrection*shadowMapSizeInverse,0.,0.);float random=getRand(vPositionFromLight.xy);float rotationAngle=random*3.1415926;vec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));float shadow=0.;for (int i=0; i<pcfTapCount; i++) {vec4 offset=vec4(poissonSamplers[i],0.);offset=vec4(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.,0.);shadow+=texture2D(shadowSampler,uvDepthLayer+offset*filterRadius);}\nshadow/=float(pcfTapCount);shadow=mix(shadow,1.,min((depthMetric-avgBlockerDepth)*depthCorrection*penumbraDarkness,1.));shadow=mix(darkness,1.,shadow);if (numBlocker<1.0) {return 1.0;}\nelse\n{return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}\n#define inline\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,highp sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\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 blockerDepth=0.0;float sumBlockerDepth=0.0;float numBlocker=0.0;for (int i=0; i<searchTapCount; i ++) {blockerDepth=TEXTUREFUNC(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy),0.).r;if (blockerDepth<depthMetric) {sumBlockerDepth+=blockerDepth;numBlocker++;}}\nif (numBlocker<1.0) {return 1.0;}\nelse\n{float avgBlockerDepth=sumBlockerDepth/numBlocker;float AAOffset=shadowMapSizeInverse*10.;float penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);float filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;float random=getRand(vPositionFromLight.xy);float rotationAngle=random*3.1415926;vec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));float shadow=0.;for (int i=0; i<pcfTapCount; i++) {vec3 offset=poissonSamplers[i];offset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);shadow+=TEXTUREFUNC(shadowSampler,uvDepth+offset*filterRadius,0.);}\nshadow/=float(pcfTapCount);shadow=mix(shadow,1.,depthMetric-avgBlockerDepth);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}}\n#define inline\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,highp sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);}\n#define inline\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,highp sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);}\n#define inline\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,highp sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);}\n#define inline\nfloat computeShadowWithCSMPCSS16(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness)\n{return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32,lightSizeUVCorrection,depthCorrection,penumbraDarkness);}\n#define inline\nfloat computeShadowWithCSMPCSS32(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness)\n{return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32,lightSizeUVCorrection,depthCorrection,penumbraDarkness);}\n#define inline\nfloat computeShadowWithCSMPCSS64(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness)\n{return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64,lightSizeUVCorrection,depthCorrection,penumbraDarkness);}\n#endif\n#endif\n";Je.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;}";Je.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}";Je.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<outsideIOR) phi12=PI;float phi21=PI-phi12;vec3 baseIOR=getIORTfromAirToSurfaceR0(clamp(baseF0,0.0,0.9999)); \nvec3 R1=getR0fromIORs(baseIOR,iridescenceIOR);vec3 R23=fresnelSchlickGGX(cosTheta2,R1,vec3(1.));vec3 phi23=vec3(0.0);if (baseIOR[0]<iridescenceIOR) phi23[0]=PI;if (baseIOR[1]<iridescenceIOR) phi23[1]=PI;if (baseIOR[2]<iridescenceIOR) phi23[2]=PI;float opd=2.0*iridescenceIOR*thinFilmThickness*cosTheta2;vec3 phi=vec3(phi21)+phi23;vec3 R123=clamp(R12*R23,1e-5,0.9999);vec3 r123=sqrt(R123);vec3 Rs=square(T121)*R23/(vec3(1.0)-R123);vec3 C0=R12+Rs;I=C0;vec3 Cm=Rs-T121;for (int m=1; m<=2; ++m)\n{Cm*=r123;vec3 Sm=2.0*evalSensitivity(float(m)*opd,float(m)*phi);I+=Cm*Sm;}\nreturn max(I,vec3(0.0));}\n#endif\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{float a2=square(alphaG);float d=NdotH*NdotH*(a2-1.0)+1.0;return a2/(PI*d*d);}\n#ifdef SHEEN\nfloat normalDistributionFunction_CharlieSheen(float NdotH,float alphaG)\n{float invR=1./alphaG;float cos2h=NdotH*NdotH;float sin2h=1.-cos2h;return (2.+invR)*pow(sin2h,invR*.5)/(2.*PI);}\n#endif\n#ifdef ANISOTROPIC\nfloat normalDistributionFunction_BurleyGGX_Anisotropic(float NdotH,float TdotH,float BdotH,const vec2 alphaTB) {float a2=alphaTB.x*alphaTB.y;vec3 v=vec3(alphaTB.y*TdotH,alphaTB.x *BdotH,a2*NdotH);float v2=dot(v,v);float w2=a2/v2;return a2*w2*w2*RECIPROCAL_PI;}\n#endif\n#ifdef BRDF_V_HEIGHT_CORRELATED\nfloat smithVisibility_GGXCorrelated(float NdotL,float NdotV,float alphaG) {\n#ifdef MOBILE\nfloat GGXV=NdotL*(NdotV*(1.0-alphaG)+alphaG);float GGXL=NdotV*(NdotL*(1.0-alphaG)+alphaG);return 0.5/(GGXV+GGXL);\n#else\nfloat a2=alphaG*alphaG;float GGXV=NdotL*sqrt(NdotV*(NdotV-a2*NdotV)+a2);float GGXL=NdotV*sqrt(NdotL*(NdotL-a2*NdotL)+a2);return 0.5/(GGXV+GGXL);\n#endif\n}\n#else\nfloat smithVisibilityG1_TrowbridgeReitzGGXFast(float dot,float alphaG)\n{\n#ifdef MOBILE\nreturn 1.0/(dot+alphaG+(1.0-alphaG)*dot ));\n#else\nfloat alphaSquared=alphaG*alphaG;return 1.0/(dot+sqrt(alphaSquared+(1.0-alphaSquared)*dot*dot));\n#endif\n}\nfloat smithVisibility_TrowbridgeReitzGGXFast(float NdotL,float NdotV,float alphaG)\n{float visibility=smithVisibilityG1_TrowbridgeReitzGGXFast(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGXFast(NdotV,alphaG);return visibility;}\n#endif\n#ifdef ANISOTROPIC\nfloat smithVisibility_GGXCorrelated_Anisotropic(float NdotL,float NdotV,float TdotV,float BdotV,float TdotL,float BdotL,const vec2 alphaTB) {float lambdaV=NdotL*length(vec3(alphaTB.x*TdotV,alphaTB.y*BdotV,NdotV));float lambdaL=NdotV*length(vec3(alphaTB.x*TdotL,alphaTB.y*BdotL,NdotL));float v=0.5/(lambdaV+lambdaL);return v;}\n#endif\n#ifdef CLEARCOAT\nfloat visibility_Kelemen(float VdotH) {return 0.25/(VdotH*VdotH); }\n#endif\n#ifdef SHEEN\nfloat visibility_Ashikhmin(float NdotL,float NdotV)\n{return 1./(4.*(NdotL+NdotV-NdotL*NdotV));}\n/* NOT USED\n#ifdef SHEEN_SOFTER\nfloat l(float x,float alphaG)\n{float oneMinusAlphaSq=(1.0-alphaG)*(1.0-alphaG);float a=mix(21.5473,25.3245,oneMinusAlphaSq);float b=mix(3.82987,3.32435,oneMinusAlphaSq);float c=mix(0.19823,0.16801,oneMinusAlphaSq);float d=mix(-1.97760,-1.27393,oneMinusAlphaSq);float e=mix(-4.32054,-4.85967,oneMinusAlphaSq);return a/(1.0+b*pow(x,c))+d*x+e;}\nfloat lambdaSheen(float cosTheta,float alphaG)\n{return abs(cosTheta)<0.5 ? exp(l(cosTheta,alphaG)) : exp(2.0*l(0.5,alphaG)-l(1.0-cosTheta,alphaG));}\nfloat visibility_CharlieSheen(float NdotL,float NdotV,float alphaG)\n{float G=1.0/(1.0+lambdaSheen(NdotV,alphaG)+lambdaSheen(NdotL,alphaG));return G/(4.0*NdotV*NdotL);}\n#endif\n*/\n#endif\nfloat diffuseBRDF_Burley(float NdotL,float NdotV,float VdotH,float roughness) {float diffuseFresnelNV=pow5(saturateEps(1.0-NdotL));float diffuseFresnelNL=pow5(saturateEps(1.0-NdotV));float diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;float fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);return fresnel/PI;}\n#ifdef SS_TRANSLUCENCY\nvec3 transmittanceBRDF_Burley(const vec3 tintColor,const vec3 diffusionDistance,float thickness) {vec3 S=1./maxEps(diffusionDistance);vec3 temp=exp((-0.333333333*thickness)*S);return tintColor.rgb*0.25*(temp*temp*temp+3.0*temp);}\nfloat computeWrappedDiffuseNdotL(float NdotL,float w) {float t=1.0+w;float invt2=1.0/square(t);return saturate((NdotL+w)*invt2);}\n#endif\n";Je.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; i<NUM_SAMPLES; ++i)\n#else\nfor(int i=0; i<NUM_SAMPLES; ++i)\n#endif\n{vec2 Xi=hammersley(i,NUM_SAMPLES);vec3 Ls=hemisphereCosSample(Xi);Ls=normalize(Ls);vec3 Ns=vec3(0.,0.,1.);float NoL=dot(Ns,Ls);if (NoL>0.) {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; i<NUM_SAMPLES; ++i)\n#else\nfor(int i=0; i<NUM_SAMPLES; ++i)\n#endif\n{vec2 Xi=hammersley(i,NUM_SAMPLES);vec3 H=hemisphereImportanceSampleDggx(Xi,alphaG);float NoV=1.;float NoH=H.z;float NoH2=H.z*H.z;float NoL=2.*NoH2-1.;vec3 L=vec3(2.*NoH*H.x,2.*NoH*H.y,NoL);L=normalize(L);if (NoL>0.) {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";Je.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";Je.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";Je.IncludesShadersStore.bumpFragmentMainFunctions="#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";Je.IncludesShadersStore.bumpFragmentFunctions="#if defined(BUMP)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_SAMPLERNAME_,bump)\n#endif\n#if defined(DETAIL)\n#include<samplerFragmentDeclaration>(_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; i<iMaxSamples; i++)\n{currSampledHeight=texture2D(bumpSampler,texCoord+vCurrOffset).w;if (!keepWorking)\n{}\nelse if (currSampledHeight>currRayHeight)\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";Je.IncludesShadersStore.reflectionFunction="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";Je.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";Je.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<decalFragment>\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<decalFragment>\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<ALPHATESTVALUE)\ndiscard;\n#endif\n#ifndef ALPHABLEND\nalpha=1.0;\n#endif\n#endif\n#endif\noutParams.surfaceAlbedo=surfaceAlbedo;outParams.alpha=alpha;return outParams;}\n";Je.IncludesShadersStore.pbrBlockReflectivity="struct reflectivityOutParams\n{float microSurface;float roughness;vec3 surfaceReflectivityColor;\n#ifdef METALLICWORKFLOW\nvec3 surfaceAlbedo;\n#endif\n#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)\nvec3 ambientOcclusionColor;\n#endif\n#if DEBUGMODE>0\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap;\n#endif\n#ifndef FROSTBITE_REFLECTANCE\nvec3 metallicF0;\n#endif\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap;\n#endif\n#endif\n#endif\n};\n#define pbr_inline\nreflectivityOutParams reflectivityBlock(\nin vec4 vReflectivityColor\n#ifdef METALLICWORKFLOW\n,in vec3 surfaceAlbedo\n,in vec4 metallicReflectanceFactors\n#endif\n#ifdef REFLECTIVITY\n,in vec3 reflectivityInfos\n,in vec4 surfaceMetallicOrReflectivityColorMap\n#endif\n#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)\n,in vec3 ambientOcclusionColorIn\n#endif\n#ifdef MICROSURFACEMAP\n,in vec4 microSurfaceTexel\n#endif\n#ifdef DETAIL\n,in vec4 detailColor\n,in vec4 vDetailInfos\n#endif\n)\n{reflectivityOutParams outParams;float microSurface=vReflectivityColor.a;vec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\n#if DEBUGMODE>0\noutParams.surfaceMetallicColorMap=surfaceMetallicOrReflectivityColorMap;\n#endif\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicOrReflectivityColorMap.r,surfaceMetallicOrReflectivityColorMap.r,surfaceMetallicOrReflectivityColorMap.r);outParams.ambientOcclusionColor=mix(ambientOcclusionColorIn,aoStoreInMetalMap,reflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicOrReflectivityColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicOrReflectivityColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicOrReflectivityColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicOrReflectivityColorMap.g;\n#endif\n#endif\n#endif\n#ifdef DETAIL\nfloat detailRoughness=mix(0.5,detailColor.b,vDetailInfos.w);float loLerp=mix(0.,metallicRoughness.g,detailRoughness*2.);float hiLerp=mix(metallicRoughness.g,1.,(detailRoughness-0.5)*2.);metallicRoughness.g=mix(loLerp,hiLerp,step(detailRoughness,0.5));\n#endif\n#ifdef MICROSURFACEMAP\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n#if DEBUGMODE>0\noutParams.metallicRoughness=metallicRoughness;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_METALLICROUGHNESS\nmicroSurface=1.0-metallicRoughness.g;vec3 baseColor=surfaceAlbedo;\n#ifdef FROSTBITE_REFLECTANCE\noutParams.surfaceAlbedo=baseColor.rgb*(1.0-metallicRoughness.r);surfaceReflectivityColor=mix(0.16*reflectance*reflectance,baseColor,metallicRoughness.r);\n#else\nvec3 metallicF0=metallicReflectanceFactors.rgb;\n#if DEBUGMODE>0\noutParams.metallicF0=metallicF0;\n#endif\noutParams.surfaceAlbedo=mix(baseColor.rgb*(1.0-metallicF0),vec3(0.,0.,0.),metallicRoughness.r);surfaceReflectivityColor=mix(metallicF0,baseColor,metallicRoughness.r);\n#endif\n#else\n#ifdef REFLECTIVITY\nsurfaceReflectivityColor*=surfaceMetallicOrReflectivityColorMap.rgb;\n#if DEBUGMODE>0\noutParams.surfaceReflectivityColorMap=surfaceMetallicOrReflectivityColorMap;\n#endif\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceMetallicOrReflectivityColorMap.a;microSurface*=reflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_MICROSURFACE\n#endif\n#endif\n#endif\nmicroSurface=saturate(microSurface);float roughness=1.-microSurface;outParams.microSurface=microSurface;outParams.roughness=roughness;outParams.surfaceReflectivityColor=surfaceReflectivityColor;return outParams;}\n";Je.IncludesShadersStore.pbrBlockAmbientOcclusion="struct ambientOcclusionOutParams\n{vec3 ambientOcclusionColor;\n#if DEBUGMODE>0 && defined(AMBIENT)\nvec3 ambientOcclusionColorMap;\n#endif\n};ambientOcclusionOutParams ambientOcclusionBlock(\n#ifdef AMBIENT\nin vec3 ambientOcclusionColorMap_,\nin vec4 vAmbientInfos\n#endif\n)\n{ambientOcclusionOutParams outParams;vec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=ambientOcclusionColorMap_*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#if DEBUGMODE>0\noutParams.ambientOcclusionColorMap=ambientOcclusionColorMap;\n#endif\n#endif\noutParams.ambientOcclusionColor=ambientOcclusionColor;return outParams;}\n";Je.IncludesShadersStore.pbrBlockAlphaFresnel="#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\nstruct alphaFresnelOutParams\n{float alpha;};\n#define pbr_inline\nalphaFresnelOutParams alphaFresnelBlock(\nin vec3 normalW,\nin vec3 viewDirectionW,\nin float alpha,\nin float microSurface\n)\n{alphaFresnelOutParams outParams;float opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);vec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);outParams.alpha=getReflectanceFromAnalyticalBRDFLookup_Jones(saturate(dot(viewDirectionW,normalForward)),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (outParams.alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\noutParams.alpha=1.0;\n#endif\n#endif\nreturn outParams;}\n#endif\n#endif\n";Je.IncludesShadersStore.pbrBlockAnisotropic="#ifdef ANISOTROPIC\nstruct anisotropicOutParams\n{float anisotropy;vec3 anisotropicTangent;vec3 anisotropicBitangent;vec3 anisotropicNormal;\n#if DEBUGMODE>0 && defined(ANISOTROPIC_TEXTURE)\nvec3 anisotropyMapData;\n#endif\n};\n#define pbr_inline\nanisotropicOutParams anisotropicBlock(\nin vec3 vAnisotropy,\nin float roughness,\n#ifdef ANISOTROPIC_TEXTURE\nin vec3 anisotropyMapData,\n#endif\nin mat3 TBN,\nin vec3 normalW,\nin vec3 viewDirectionW\n)\n{anisotropicOutParams outParams;float anisotropy=vAnisotropy.b;vec3 anisotropyDirection=vec3(vAnisotropy.xy,0.);\n#ifdef ANISOTROPIC_TEXTURE\nanisotropy*=anisotropyMapData.b;\n#if DEBUGMODE>0\noutParams.anisotropyMapData=anisotropyMapData;\n#endif\nanisotropyMapData.rg=anisotropyMapData.rg*2.0-1.0;\n#ifdef ANISOTROPIC_LEGACY\nanisotropyDirection.rg*=anisotropyMapData.rg;\n#else\nanisotropyDirection.xy=mat2(anisotropyDirection.x,anisotropyDirection.y,-anisotropyDirection.y,anisotropyDirection.x)*normalize(anisotropyMapData.rg);\n#endif\n#endif\nmat3 anisoTBN=mat3(normalize(TBN[0]),normalize(TBN[1]),normalize(TBN[2]));vec3 anisotropicTangent=normalize(anisoTBN*anisotropyDirection);vec3 anisotropicBitangent=normalize(cross(anisoTBN[2],anisotropicTangent));outParams.anisotropy=anisotropy;outParams.anisotropicTangent=anisotropicTangent;outParams.anisotropicBitangent=anisotropicBitangent;outParams.anisotropicNormal=getAnisotropicBentNormals(anisotropicTangent,anisotropicBitangent,normalW,viewDirectionW,anisotropy,roughness);return outParams;}\n#endif\n";Je.IncludesShadersStore.pbrBlockReflection="#ifdef REFLECTION\nstruct reflectionOutParams\n{vec4 environmentRadiance;vec3 environmentIrradiance;\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords;\n#else\nvec2 reflectionCoords;\n#endif\n#ifdef SS_TRANSLUCENCY\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)\nvec3 irradianceVector;\n#endif\n#endif\n#endif\n};\n#define pbr_inline\nvoid createReflectionCoords(\nin vec3 vPositionW,\nin vec3 normalW,\n#ifdef ANISOTROPIC\nin anisotropicOutParams anisotropicOut,\n#endif\n#ifdef REFLECTIONMAP_3D\nout vec3 reflectionCoords\n#else\nout vec2 reflectionCoords\n#endif\n)\n{\n#ifdef ANISOTROPIC\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),anisotropicOut.anisotropicNormal);\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\nreflectionCoords=reflectionVector;\n#else\nreflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n}\n#define pbr_inline\n#define inline\nvoid sampleReflectionTexture(\nin float alphaG,\nin vec3 vReflectionMicrosurfaceInfos,\nin vec2 vReflectionInfos,\nin vec3 vReflectionColor,\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nin float NdotVUnclamped,\n#endif\n#ifdef LINEARSPECULARREFLECTION\nin float roughness,\n#endif\n#ifdef REFLECTIONMAP_3D\nin samplerCube reflectionSampler,\nconst vec3 reflectionCoords,\n#else\nin sampler2D reflectionSampler,\nconst vec2 reflectionCoords,\n#endif\n#ifndef LODBASEDMICROSFURACE\n#ifdef REFLECTIONMAP_3D\nin samplerCube reflectionSamplerLow,\nin samplerCube reflectionSamplerHigh,\n#else\nin sampler2D reflectionSamplerLow,\nin sampler2D reflectionSamplerHigh,\n#endif\n#endif\n#ifdef REALTIME_FILTERING\nin vec2 vReflectionFilteringInfo,\n#endif\nout vec4 environmentRadiance\n)\n{\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#elif defined(LINEARSPECULARREFLECTION)\nfloat reflectionLOD=getLinearLodFromRoughness(vReflectionMicrosurfaceInfos.x,roughness);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG);\n#endif\n#ifdef LODBASEDMICROSFURACE\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);float requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\n#ifdef REALTIME_FILTERING\nenvironmentRadiance=vec4(radiance(alphaG,reflectionSampler,reflectionCoords,vReflectionFilteringInfo),1.0);\n#else\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);\n#endif\n#else\nfloat lodReflectionNormalized=saturate(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x));float lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;vec4 environmentMid=sampleReflection(reflectionSampler,reflectionCoords);if (lodReflectionNormalizedDoubled<1.0){environmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nenvironmentMid,\nlodReflectionNormalizedDoubled\n);} else {environmentRadiance=mix(\nenvironmentMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);}\n#endif\n#ifdef RGBDREFLECTION\nenvironmentRadiance.rgb=fromRGBD(environmentRadiance);\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance.rgb=toLinearSpace(environmentRadiance.rgb);\n#endif\nenvironmentRadiance.rgb*=vReflectionInfos.x;environmentRadiance.rgb*=vReflectionColor.rgb;}\n#define pbr_inline\n#define inline\nreflectionOutParams reflectionBlock(\nin vec3 vPositionW\n,in vec3 normalW\n,in float alphaG\n,in vec3 vReflectionMicrosurfaceInfos\n,in vec2 vReflectionInfos\n,in vec3 vReflectionColor\n#ifdef ANISOTROPIC\n,in anisotropicOutParams anisotropicOut\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\n,in float NdotVUnclamped\n#endif\n#ifdef LINEARSPECULARREFLECTION\n,in float roughness\n#endif\n#ifdef REFLECTIONMAP_3D\n,in samplerCube reflectionSampler\n#else\n,in sampler2D reflectionSampler\n#endif\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\n,in vec3 vEnvironmentIrradiance\n#endif\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)\n,in mat4 reflectionMatrix\n#endif\n#endif\n#ifdef USEIRRADIANCEMAP\n#ifdef REFLECTIONMAP_3D\n,in samplerCube irradianceSampler\n#else\n,in sampler2D irradianceSampler\n#endif\n#endif\n#ifndef LODBASEDMICROSFURACE\n#ifdef REFLECTIONMAP_3D\n,in samplerCube reflectionSamplerLow\n,in samplerCube reflectionSamplerHigh\n#else\n,in sampler2D reflectionSamplerLow\n,in sampler2D reflectionSamplerHigh\n#endif\n#endif\n#ifdef REALTIME_FILTERING\n,in vec2 vReflectionFilteringInfo\n#endif\n)\n{reflectionOutParams outParams;vec4 environmentRadiance=vec4(0.,0.,0.,0.);\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=vec3(0.);\n#else\nvec2 reflectionCoords=vec2(0.);\n#endif\ncreateReflectionCoords(\nvPositionW,\nnormalW,\n#ifdef ANISOTROPIC\nanisotropicOut,\n#endif\nreflectionCoords\n);sampleReflectionTexture(\nalphaG,\nvReflectionMicrosurfaceInfos,\nvReflectionInfos,\nvReflectionColor,\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nNdotVUnclamped,\n#endif\n#ifdef LINEARSPECULARREFLECTION\nroughness,\n#endif\n#ifdef REFLECTIONMAP_3D\nreflectionSampler,\nreflectionCoords,\n#else\nreflectionSampler,\nreflectionCoords,\n#endif\n#ifndef LODBASEDMICROSFURACE\nreflectionSamplerLow,\nreflectionSamplerHigh,\n#endif\n#ifdef REALTIME_FILTERING\nvReflectionFilteringInfo,\n#endif\nenvironmentRadiance\n);vec3 environmentIrradiance=vec3(0.,0.,0.);\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\n#ifdef ANISOTROPIC\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(anisotropicOut.anisotropicNormal,0)).xyz;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#endif\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\n#ifdef INVERTCUBICMAP\nirradianceVector.y*=-1.0;\n#endif\n#if defined(REALTIME_FILTERING)\nenvironmentIrradiance=irradiance(reflectionSampler,irradianceVector,vReflectionFilteringInfo);\n#else\nenvironmentIrradiance=computeEnvironmentIrradiance(irradianceVector);\n#endif\n#ifdef SS_TRANSLUCENCY\noutParams.irradianceVector=irradianceVector;\n#endif\n#endif\n#elif defined(USEIRRADIANCEMAP)\nvec4 environmentIrradiance4=sampleReflection(irradianceSampler,reflectionCoords);environmentIrradiance=environmentIrradiance4.rgb;\n#ifdef RGBDREFLECTION\nenvironmentIrradiance.rgb=fromRGBD(environmentIrradiance4);\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentIrradiance.rgb=toLinearSpace(environmentIrradiance.rgb);\n#endif\n#endif\nenvironmentIrradiance*=vReflectionColor.rgb;outParams.environmentRadiance=environmentRadiance;outParams.environmentIrradiance=environmentIrradiance;outParams.reflectionCoords=reflectionCoords;return outParams;}\n#endif\n";Je.IncludesShadersStore.pbrBlockSheen="#ifdef SHEEN\nstruct sheenOutParams\n{float sheenIntensity;vec3 sheenColor;float sheenRoughness;\n#ifdef SHEEN_LINKWITHALBEDO\nvec3 surfaceAlbedo;\n#endif\n#if defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING)\nfloat sheenAlbedoScaling;\n#endif\n#if defined(REFLECTION) && defined(ENVIRONMENTBRDF)\nvec3 finalSheenRadianceScaled;\n#endif\n#if DEBUGMODE>0\n#ifdef SHEEN_TEXTURE\nvec4 sheenMapData;\n#endif\n#if defined(REFLECTION) && defined(ENVIRONMENTBRDF)\nvec3 sheenEnvironmentReflectance;\n#endif\n#endif\n};\n#define pbr_inline\n#define inline\nsheenOutParams sheenBlock(\nin vec4 vSheenColor\n#ifdef SHEEN_ROUGHNESS\n,in float vSheenRoughness\n#if defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE)\n,in vec4 sheenMapRoughnessData\n#endif\n#endif\n,in float roughness\n#ifdef SHEEN_TEXTURE\n,in vec4 sheenMapData\n,in float sheenMapLevel\n#endif\n,in float reflectance\n#ifdef SHEEN_LINKWITHALBEDO\n,in vec3 baseColor\n,in vec3 surfaceAlbedo\n#endif\n#ifdef ENVIRONMENTBRDF\n,in float NdotV\n,in vec3 environmentBrdf\n#endif\n#if defined(REFLECTION) && defined(ENVIRONMENTBRDF)\n,in vec2 AARoughnessFactors\n,in vec3 vReflectionMicrosurfaceInfos\n,in vec2 vReflectionInfos\n,in vec3 vReflectionColor\n,in vec4 vLightingIntensity\n#ifdef REFLECTIONMAP_3D\n,in samplerCube reflectionSampler\n,in vec3 reflectionCoords\n#else\n,in sampler2D reflectionSampler\n,in vec2 reflectionCoords\n#endif\n,in float NdotVUnclamped\n#ifndef LODBASEDMICROSFURACE\n#ifdef REFLECTIONMAP_3D\n,in samplerCube reflectionSamplerLow\n,in samplerCube reflectionSamplerHigh\n#else\n,in sampler2D reflectionSamplerLow\n,in sampler2D reflectionSamplerHigh\n#endif\n#endif\n#ifdef REALTIME_FILTERING\n,in vec2 vReflectionFilteringInfo\n#endif\n#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION)\n,in float seo\n#endif\n#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D)\n,in float eho\n#endif\n#endif\n)\n{sheenOutParams outParams;float sheenIntensity=vSheenColor.a;\n#ifdef SHEEN_TEXTURE\n#if DEBUGMODE>0\noutParams.sheenMapData=sheenMapData;\n#endif\n#endif\n#ifdef SHEEN_LINKWITHALBEDO\nfloat sheenFactor=pow5(1.0-sheenIntensity);vec3 sheenColor=baseColor.rgb*(1.0-sheenFactor);float sheenRoughness=sheenIntensity;outParams.surfaceAlbedo=surfaceAlbedo*sheenFactor;\n#ifdef SHEEN_TEXTURE\nsheenIntensity*=sheenMapData.a;\n#endif\n#else\nvec3 sheenColor=vSheenColor.rgb;\n#ifdef SHEEN_TEXTURE\n#ifdef SHEEN_GAMMATEXTURE\nsheenColor.rgb*=toLinearSpace(sheenMapData.rgb);\n#else\nsheenColor.rgb*=sheenMapData.rgb;\n#endif\nsheenColor.rgb*=sheenMapLevel;\n#endif\n#ifdef SHEEN_ROUGHNESS\nfloat sheenRoughness=vSheenRoughness;\n#ifdef SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE\n#if defined(SHEEN_TEXTURE)\nsheenRoughness*=sheenMapData.a;\n#endif\n#elif defined(SHEEN_TEXTURE_ROUGHNESS)\nsheenRoughness*=sheenMapRoughnessData.a;\n#endif\n#else\nfloat sheenRoughness=roughness;\n#ifdef SHEEN_TEXTURE\nsheenIntensity*=sheenMapData.a;\n#endif\n#endif\n#if !defined(SHEEN_ALBEDOSCALING)\nsheenIntensity*=(1.-reflectance);\n#endif\nsheenColor*=sheenIntensity;\n#endif\n#ifdef ENVIRONMENTBRDF\n/*#ifdef SHEEN_SOFTER\nvec3 environmentSheenBrdf=vec3(0.,0.,getBRDFLookupCharlieSheen(NdotV,sheenRoughness));\n#else*/\n#ifdef SHEEN_ROUGHNESS\nvec3 environmentSheenBrdf=getBRDFLookup(NdotV,sheenRoughness);\n#else\nvec3 environmentSheenBrdf=environmentBrdf;\n#endif\n/*#endif*/\n#endif\n#if defined(REFLECTION) && defined(ENVIRONMENTBRDF)\nfloat sheenAlphaG=convertRoughnessToAverageSlope(sheenRoughness);\n#ifdef SPECULARAA\nsheenAlphaG+=AARoughnessFactors.y;\n#endif\nvec4 environmentSheenRadiance=vec4(0.,0.,0.,0.);sampleReflectionTexture(\nsheenAlphaG,\nvReflectionMicrosurfaceInfos,\nvReflectionInfos,\nvReflectionColor,\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nNdotVUnclamped,\n#endif\n#ifdef LINEARSPECULARREFLECTION\nsheenRoughness,\n#endif\nreflectionSampler,\nreflectionCoords,\n#ifndef LODBASEDMICROSFURACE\nreflectionSamplerLow,\nreflectionSamplerHigh,\n#endif\n#ifdef REALTIME_FILTERING\nvReflectionFilteringInfo,\n#endif\nenvironmentSheenRadiance\n);vec3 sheenEnvironmentReflectance=getSheenReflectanceFromBRDFLookup(sheenColor,environmentSheenBrdf);\n#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION)\nsheenEnvironmentReflectance*=seo;\n#endif\n#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D)\nsheenEnvironmentReflectance*=eho;\n#endif\n#if DEBUGMODE>0\noutParams.sheenEnvironmentReflectance=sheenEnvironmentReflectance;\n#endif\noutParams.finalSheenRadianceScaled=\nenvironmentSheenRadiance.rgb *\nsheenEnvironmentReflectance *\nvLightingIntensity.z;\n#endif\n#if defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING)\noutParams.sheenAlbedoScaling=1.0-sheenIntensity*max(max(sheenColor.r,sheenColor.g),sheenColor.b)*environmentSheenBrdf.b;\n#endif\noutParams.sheenIntensity=sheenIntensity;outParams.sheenColor=sheenColor;outParams.sheenRoughness=sheenRoughness;return outParams;}\n#endif\n";Je.IncludesShadersStore.pbrBlockClearcoat="struct clearcoatOutParams\n{vec3 specularEnvironmentR0;float conservationFactor;vec3 clearCoatNormalW;vec2 clearCoatAARoughnessFactors;float clearCoatIntensity;float clearCoatRoughness;\n#ifdef REFLECTION\nvec3 finalClearCoatRadianceScaled;\n#endif\n#ifdef CLEARCOAT_TINT\nvec3 absorption;float clearCoatNdotVRefract;vec3 clearCoatColor;float clearCoatThickness;\n#endif\n#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)\nvec3 energyConservationFactorClearCoat;\n#endif\n#if DEBUGMODE>0\n#ifdef CLEARCOAT_BUMP\nmat3 TBNClearCoat;\n#endif\n#ifdef CLEARCOAT_TEXTURE\nvec2 clearCoatMapData;\n#endif\n#if defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE)\nvec4 clearCoatTintMapData;\n#endif\n#ifdef REFLECTION\nvec4 environmentClearCoatRadiance;vec3 clearCoatEnvironmentReflectance;\n#endif\nfloat clearCoatNdotV;\n#endif\n};\n#ifdef CLEARCOAT\n#define pbr_inline\n#define inline\nclearcoatOutParams clearcoatBlock(\nin vec3 vPositionW\n,in vec3 geometricNormalW\n,in vec3 viewDirectionW\n,in vec2 vClearCoatParams\n#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE)\n,in vec4 clearCoatMapRoughnessData\n#endif\n,in vec3 specularEnvironmentR0\n#ifdef CLEARCOAT_TEXTURE\n,in vec2 clearCoatMapData\n#endif\n#ifdef CLEARCOAT_TINT\n,in vec4 vClearCoatTintParams\n,in float clearCoatColorAtDistance\n,in vec4 vClearCoatRefractionParams\n#ifdef CLEARCOAT_TINT_TEXTURE\n,in vec4 clearCoatTintMapData\n#endif\n#endif\n#ifdef CLEARCOAT_BUMP\n,in vec2 vClearCoatBumpInfos\n,in vec4 clearCoatBumpMapData\n,in vec2 vClearCoatBumpUV\n#if defined(TANGENT) && defined(NORMAL)\n,in mat3 vTBN\n#else\n,in vec2 vClearCoatTangentSpaceParams\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\n,in mat4 normalMatrix\n#endif\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\n,in vec3 faceNormal\n#endif\n#ifdef REFLECTION\n,in vec3 vReflectionMicrosurfaceInfos\n,in vec2 vReflectionInfos\n,in vec3 vReflectionColor\n,in vec4 vLightingIntensity\n#ifdef REFLECTIONMAP_3D\n,in samplerCube reflectionSampler\n#else\n,in sampler2D reflectionSampler\n#endif\n#ifndef LODBASEDMICROSFURACE\n#ifdef REFLECTIONMAP_3D\n,in samplerCube reflectionSamplerLow\n,in samplerCube reflectionSamplerHigh\n#else\n,in sampler2D reflectionSamplerLow\n,in sampler2D reflectionSamplerHigh\n#endif\n#endif\n#ifdef REALTIME_FILTERING\n,in vec2 vReflectionFilteringInfo\n#endif\n#endif\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n#ifdef RADIANCEOCCLUSION\n,in float ambientMonochrome\n#endif\n#endif\n#if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING)\n,in float frontFacingMultiplier\n#endif\n)\n{clearcoatOutParams outParams;float clearCoatIntensity=vClearCoatParams.x;float clearCoatRoughness=vClearCoatParams.y;\n#ifdef CLEARCOAT_TEXTURE\nclearCoatIntensity*=clearCoatMapData.x;\n#ifdef CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE\nclearCoatRoughness*=clearCoatMapData.y;\n#endif\n#if DEBUGMODE>0\noutParams.clearCoatMapData=clearCoatMapData;\n#endif\n#endif\n#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE)\nclearCoatRoughness*=clearCoatMapRoughnessData.y;\n#endif\noutParams.clearCoatIntensity=clearCoatIntensity;outParams.clearCoatRoughness=clearCoatRoughness;\n#ifdef CLEARCOAT_TINT\nvec3 clearCoatColor=vClearCoatTintParams.rgb;float clearCoatThickness=vClearCoatTintParams.a;\n#ifdef CLEARCOAT_TINT_TEXTURE\n#ifdef CLEARCOAT_TINT_GAMMATEXTURE\nclearCoatColor*=toLinearSpace(clearCoatTintMapData.rgb);\n#else\nclearCoatColor*=clearCoatTintMapData.rgb;\n#endif\nclearCoatThickness*=clearCoatTintMapData.a;\n#if DEBUGMODE>0\noutParams.clearCoatTintMapData=clearCoatTintMapData;\n#endif\n#endif\noutParams.clearCoatColor=computeColorAtDistanceInMedia(clearCoatColor,clearCoatColorAtDistance);outParams.clearCoatThickness=clearCoatThickness;\n#endif\n#ifdef CLEARCOAT_REMAP_F0\nvec3 specularEnvironmentR0Updated=getR0RemappedForClearCoat(specularEnvironmentR0);\n#else\nvec3 specularEnvironmentR0Updated=specularEnvironmentR0;\n#endif\noutParams.specularEnvironmentR0=mix(specularEnvironmentR0,specularEnvironmentR0Updated,clearCoatIntensity);vec3 clearCoatNormalW=geometricNormalW;\n#ifdef CLEARCOAT_BUMP\n#ifdef NORMALXYSCALE\nfloat clearCoatNormalScale=1.0;\n#else\nfloat clearCoatNormalScale=vClearCoatBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBNClearCoat=vTBN;\n#else\nvec2 TBNClearCoatUV=vClearCoatBumpUV*frontFacingMultiplier;mat3 TBNClearCoat=cotangent_frame(clearCoatNormalW*clearCoatNormalScale,vPositionW,TBNClearCoatUV,vClearCoatTangentSpaceParams);\n#endif\n#if DEBUGMODE>0\noutParams.TBNClearCoat=TBNClearCoat;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nclearCoatNormalW=normalize(clearCoatBumpMapData.xyz *2.0-1.0);clearCoatNormalW=normalize(mat3(normalMatrix)*clearCoatNormalW);\n#else\nclearCoatNormalW=perturbNormal(TBNClearCoat,clearCoatBumpMapData.xyz,vClearCoatBumpInfos.y);\n#endif\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nclearCoatNormalW*=sign(dot(clearCoatNormalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nclearCoatNormalW=clearCoatNormalW*frontFacingMultiplier;\n#endif\noutParams.clearCoatNormalW=clearCoatNormalW;outParams.clearCoatAARoughnessFactors=getAARoughnessFactors(clearCoatNormalW.xyz);float clearCoatNdotVUnclamped=dot(clearCoatNormalW,viewDirectionW);float clearCoatNdotV=absEps(clearCoatNdotVUnclamped);\n#if DEBUGMODE>0\noutParams.clearCoatNdotV=clearCoatNdotV;\n#endif\n#ifdef CLEARCOAT_TINT\nvec3 clearCoatVRefract=refract(-viewDirectionW,clearCoatNormalW,vClearCoatRefractionParams.y);outParams.clearCoatNdotVRefract=absEps(dot(clearCoatNormalW,clearCoatVRefract));\n#endif\n#if defined(ENVIRONMENTBRDF) && (!defined(REFLECTIONMAP_SKYBOX) || defined(MS_BRDF_ENERGY_CONSERVATION))\nvec3 environmentClearCoatBrdf=getBRDFLookup(clearCoatNdotV,clearCoatRoughness);\n#endif\n#if defined(REFLECTION)\nfloat clearCoatAlphaG=convertRoughnessToAverageSlope(clearCoatRoughness);\n#ifdef SPECULARAA\nclearCoatAlphaG+=outParams.clearCoatAARoughnessFactors.y;\n#endif\nvec4 environmentClearCoatRadiance=vec4(0.,0.,0.,0.);vec3 clearCoatReflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),clearCoatNormalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nclearCoatReflectionVector.z*=-1.0;\n#endif\n#ifdef REFLECTIONMAP_3D\nvec3 clearCoatReflectionCoords=clearCoatReflectionVector;\n#else\nvec2 clearCoatReflectionCoords=clearCoatReflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nclearCoatReflectionCoords/=clearCoatReflectionVector.z;\n#endif\nclearCoatReflectionCoords.y=1.0-clearCoatReflectionCoords.y;\n#endif\nsampleReflectionTexture(\nclearCoatAlphaG,\nvReflectionMicrosurfaceInfos,\nvReflectionInfos,\nvReflectionColor,\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nclearCoatNdotVUnclamped,\n#endif\n#ifdef LINEARSPECULARREFLECTION\nclearCoatRoughness,\n#endif\nreflectionSampler,\nclearCoatReflectionCoords,\n#ifndef LODBASEDMICROSFURACE\nreflectionSamplerLow,\nreflectionSamplerHigh,\n#endif\n#ifdef REALTIME_FILTERING\nvReflectionFilteringInfo,\n#endif\nenvironmentClearCoatRadiance\n);\n#if DEBUGMODE>0\noutParams.environmentClearCoatRadiance=environmentClearCoatRadiance;\n#endif\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\nvec3 clearCoatEnvironmentReflectance=getReflectanceFromBRDFLookup(vec3(vClearCoatRefractionParams.x),environmentClearCoatBrdf);\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat clearCoatEho=environmentHorizonOcclusion(-viewDirectionW,clearCoatNormalW,geometricNormalW);clearCoatEnvironmentReflectance*=clearCoatEho;\n#endif\n#endif\n#endif\n#else\nvec3 clearCoatEnvironmentReflectance=getReflectanceFromAnalyticalBRDFLookup_Jones(clearCoatNdotV,vec3(1.),vec3(1.),sqrt(1.-clearCoatRoughness));\n#endif\nclearCoatEnvironmentReflectance*=clearCoatIntensity;\n#if DEBUGMODE>0\noutParams.clearCoatEnvironmentReflectance=clearCoatEnvironmentReflectance;\n#endif\noutParams.finalClearCoatRadianceScaled=\nenvironmentClearCoatRadiance.rgb *\nclearCoatEnvironmentReflectance *\nvLightingIntensity.z;\n#endif\n#if defined(CLEARCOAT_TINT)\noutParams.absorption=computeClearCoatAbsorption(outParams.clearCoatNdotVRefract,outParams.clearCoatNdotVRefract,outParams.clearCoatColor,clearCoatThickness,clearCoatIntensity);\n#endif\nfloat fresnelIBLClearCoat=fresnelSchlickGGX(clearCoatNdotV,vClearCoatRefractionParams.x,CLEARCOATREFLECTANCE90);fresnelIBLClearCoat*=clearCoatIntensity;outParams.conservationFactor=(1.-fresnelIBLClearCoat);\n#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)\noutParams.energyConservationFactorClearCoat=getEnergyConservationFactor(outParams.specularEnvironmentR0,environmentClearCoatBrdf);\n#endif\nreturn outParams;}\n#endif\n";Je.IncludesShadersStore.pbrBlockIridescence="struct iridescenceOutParams\n{float iridescenceIntensity;float iridescenceIOR;float iridescenceThickness;vec3 specularEnvironmentR0;};\n#ifdef IRIDESCENCE\n#define pbr_inline\n#define inline\niridescenceOutParams iridescenceBlock(\nin vec4 vIridescenceParams\n,in float viewAngle\n,in vec3 specularEnvironmentR0\n#ifdef IRIDESCENCE_TEXTURE\n,in vec2 iridescenceMapData\n#endif\n#ifdef IRIDESCENCE_THICKNESS_TEXTURE\n,in vec2 iridescenceThicknessMapData\n#endif\n#ifdef CLEARCOAT\n,in float NdotVUnclamped\n#ifdef CLEARCOAT_TEXTURE\n,in vec2 clearCoatMapData\n#endif\n#endif\n)\n{iridescenceOutParams outParams;float iridescenceIntensity=vIridescenceParams.x;float iridescenceIOR=vIridescenceParams.y;float iridescenceThicknessMin=vIridescenceParams.z;float iridescenceThicknessMax=vIridescenceParams.w;float iridescenceThicknessWeight=1.;\n#ifdef IRIDESCENCE_TEXTURE\niridescenceIntensity*=iridescenceMapData.x;\n#endif\n#if defined(IRIDESCENCE_THICKNESS_TEXTURE)\niridescenceThicknessWeight=iridescenceThicknessMapData.g;\n#endif\nfloat iridescenceThickness=mix(iridescenceThicknessMin,iridescenceThicknessMax,iridescenceThicknessWeight);float topIor=1.; \n#ifdef CLEARCOAT\nfloat clearCoatIntensity=vClearCoatParams.x;\n#ifdef CLEARCOAT_TEXTURE\nclearCoatIntensity*=clearCoatMapData.x;\n#endif\ntopIor=mix(1.0,vClearCoatRefractionParams.w-1.,clearCoatIntensity);viewAngle=sqrt(1.0+square(1.0/topIor)*(square(NdotVUnclamped)-1.0));\n#endif\nvec3 iridescenceFresnel=evalIridescence(topIor,iridescenceIOR,viewAngle,iridescenceThickness,specularEnvironmentR0);outParams.specularEnvironmentR0=mix(specularEnvironmentR0,iridescenceFresnel,iridescenceIntensity);outParams.iridescenceIntensity=iridescenceIntensity;outParams.iridescenceThickness=iridescenceThickness;outParams.iridescenceIOR=iridescenceIOR;return outParams;}\n#endif\n";Je.IncludesShadersStore.pbrBlockSubSurface="struct subSurfaceOutParams\n{vec3 specularEnvironmentReflectance;\n#ifdef SS_REFRACTION\nvec3 finalRefraction;vec3 surfaceAlbedo;\n#ifdef SS_LINKREFRACTIONTOTRANSPARENCY\nfloat alpha;\n#endif\n#ifdef REFLECTION\nfloat refractionFactorForIrradiance;\n#endif\n#endif\n#ifdef SS_TRANSLUCENCY\nvec3 transmittance;float translucencyIntensity;\n#ifdef REFLECTION\nvec3 refractionIrradiance;\n#endif\n#endif\n#if DEBUGMODE>0\n#ifdef SS_THICKNESSANDMASK_TEXTURE\nvec4 thicknessMap;\n#endif\n#ifdef SS_REFRACTION\nvec4 environmentRefraction;vec3 refractionTransmittance;\n#endif\n#endif\n};\n#ifdef SUBSURFACE\n#ifdef SS_REFRACTION\n#define pbr_inline\n#define inline\nvec4 sampleEnvironmentRefraction(\nin float ior\n,in float thickness\n,in float refractionLOD\n,in vec3 normalW\n,in vec3 vPositionW\n,in vec3 viewDirectionW\n,in mat4 view\n,in vec4 vRefractionInfos\n,in mat4 refractionMatrix\n,in vec4 vRefractionMicrosurfaceInfos\n,in float alphaG\n#ifdef SS_REFRACTIONMAP_3D\n,in samplerCube refractionSampler\n#ifndef LODBASEDMICROSFURACE\n,in samplerCube refractionSamplerLow\n,in samplerCube refractionSamplerHigh\n#endif\n#else\n,in sampler2D refractionSampler\n#ifndef LODBASEDMICROSFURACE\n,in sampler2D refractionSamplerLow\n,in sampler2D refractionSamplerHigh\n#endif\n#endif\n#ifdef ANISOTROPIC\n,in anisotropicOutParams anisotropicOut\n#endif\n#ifdef REALTIME_FILTERING\n,in vec2 vRefractionFilteringInfo\n#endif\n#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC\n,in vec3 refractionPosition\n,in vec3 refractionSize\n#endif\n) {vec4 environmentRefraction=vec4(0.,0.,0.,0.);\n#ifdef ANISOTROPIC\nvec3 refractionVector=refract(-viewDirectionW,anisotropicOut.anisotropicNormal,ior);\n#else\nvec3 refractionVector=refract(-viewDirectionW,normalW,ior);\n#endif\n#ifdef SS_REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n#ifdef SS_REFRACTIONMAP_3D\n#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC\nrefractionVector=parallaxCorrectNormal(vPositionW,refractionVector,refractionSize,refractionPosition);\n#endif\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;vec3 refractionCoords=refractionVector;refractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\n#ifdef SS_USE_THICKNESS_AS_DEPTH\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*thickness,1.0)));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\n#endif\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;refractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODBASEDMICROSFURACE\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef SS_LODINREFRACTIONALPHA\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);float requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\n#if defined(REALTIME_FILTERING) && defined(SS_REFRACTIONMAP_3D)\nenvironmentRefraction=vec4(radiance(alphaG,refractionSampler,refractionCoords,vRefractionFilteringInfo),1.0);\n#else\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD);\n#endif\n#else\nfloat lodRefractionNormalized=saturate(refractionLOD/log2(vRefractionMicrosurfaceInfos.x));float lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;vec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);if (lodRefractionNormalizedDoubled<1.0){environmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords),\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);} else {environmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords),\nlodRefractionNormalizedDoubled-1.0\n);}\n#endif\n#ifdef SS_RGBDREFRACTION\nenvironmentRefraction.rgb=fromRGBD(environmentRefraction);\n#endif\n#ifdef SS_GAMMAREFRACTION\nenvironmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb);\n#endif\nreturn environmentRefraction;}\n#endif\n#define pbr_inline\n#define inline\nsubSurfaceOutParams subSurfaceBlock(\nin vec3 vSubSurfaceIntensity\n,in vec2 vThicknessParam\n,in vec4 vTintColor\n,in vec3 normalW\n,in vec3 specularEnvironmentReflectance\n#ifdef SS_THICKNESSANDMASK_TEXTURE\n,in vec4 thicknessMap\n#endif\n#ifdef SS_REFRACTIONINTENSITY_TEXTURE\n,in vec4 refractionIntensityMap\n#endif\n#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE\n,in vec4 translucencyIntensityMap\n#endif\n#ifdef REFLECTION\n#ifdef SS_TRANSLUCENCY\n,in mat4 reflectionMatrix\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)\n,in vec3 irradianceVector_\n#endif\n#if defined(REALTIME_FILTERING)\n,in samplerCube reflectionSampler\n,in vec2 vReflectionFilteringInfo\n#endif\n#endif\n#ifdef USEIRRADIANCEMAP\n#ifdef REFLECTIONMAP_3D\n,in samplerCube irradianceSampler\n#else\n,in sampler2D irradianceSampler\n#endif\n#endif\n#endif\n#endif\n#if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY)\n,in vec3 surfaceAlbedo\n#endif\n#ifdef SS_REFRACTION\n,in vec3 vPositionW\n,in vec3 viewDirectionW\n,in mat4 view\n,in vec4 vRefractionInfos\n,in mat4 refractionMatrix\n,in vec4 vRefractionMicrosurfaceInfos\n,in vec4 vLightingIntensity\n#ifdef SS_LINKREFRACTIONTOTRANSPARENCY\n,in float alpha\n#endif\n#ifdef SS_LODINREFRACTIONALPHA\n,in float NdotVUnclamped\n#endif\n#ifdef SS_LINEARSPECULARREFRACTION\n,in float roughness\n#endif\n,in float alphaG\n#ifdef SS_REFRACTIONMAP_3D\n,in samplerCube refractionSampler\n#ifndef LODBASEDMICROSFURACE\n,in samplerCube refractionSamplerLow\n,in samplerCube refractionSamplerHigh\n#endif\n#else\n,in sampler2D refractionSampler\n#ifndef LODBASEDMICROSFURACE\n,in sampler2D refractionSamplerLow\n,in sampler2D refractionSamplerHigh\n#endif\n#endif\n#ifdef ANISOTROPIC\n,in anisotropicOutParams anisotropicOut\n#endif\n#ifdef REALTIME_FILTERING\n,in vec2 vRefractionFilteringInfo\n#endif\n#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC\n,in vec3 refractionPosition\n,in vec3 refractionSize\n#endif\n#ifdef SS_DISPERSION\n,in float dispersion\n#endif\n#endif\n#ifdef SS_TRANSLUCENCY\n,in vec3 vDiffusionDistance\n,in vec4 vTranslucencyColor\n#ifdef SS_TRANSLUCENCYCOLOR_TEXTURE\n,in vec4 translucencyColorMap\n#endif\n#endif\n)\n{subSurfaceOutParams outParams;outParams.specularEnvironmentReflectance=specularEnvironmentReflectance;\n#ifdef SS_REFRACTION\nfloat refractionIntensity=vSubSurfaceIntensity.x;\n#ifdef SS_LINKREFRACTIONTOTRANSPARENCY\nrefractionIntensity*=(1.0-alpha);outParams.alpha=1.0;\n#endif\n#endif\n#ifdef SS_TRANSLUCENCY\nfloat translucencyIntensity=vSubSurfaceIntensity.y;\n#endif\n#ifdef SS_THICKNESSANDMASK_TEXTURE\n#ifdef SS_USE_GLTF_TEXTURES\nfloat thickness=thicknessMap.g*vThicknessParam.y+vThicknessParam.x;\n#else\nfloat thickness=thicknessMap.r*vThicknessParam.y+vThicknessParam.x;\n#endif\n#if DEBUGMODE>0\noutParams.thicknessMap=thicknessMap;\n#endif\n#if defined(SS_REFRACTION) && defined(SS_REFRACTION_USE_INTENSITY_FROM_THICKNESS)\n#ifdef SS_USE_GLTF_TEXTURES\nrefractionIntensity*=thicknessMap.r;\n#else\nrefractionIntensity*=thicknessMap.g;\n#endif\n#endif\n#if defined(SS_TRANSLUCENCY) && defined(SS_TRANSLUCENCY_USE_INTENSITY_FROM_THICKNESS)\n#ifdef SS_USE_GLTF_TEXTURES\ntranslucencyIntensity*=thicknessMap.a;\n#else\ntranslucencyIntensity*=thicknessMap.b;\n#endif\n#endif\n#else\nfloat thickness=vThicknessParam.y;\n#endif\n#if defined(SS_REFRACTION) && defined(SS_REFRACTIONINTENSITY_TEXTURE)\n#ifdef SS_USE_GLTF_TEXTURES\nrefractionIntensity*=refractionIntensityMap.r;\n#else\nrefractionIntensity*=refractionIntensityMap.g;\n#endif\n#endif\n#if defined(SS_TRANSLUCENCY) && defined(SS_TRANSLUCENCYINTENSITY_TEXTURE)\n#ifdef SS_USE_GLTF_TEXTURES\ntranslucencyIntensity*=translucencyIntensityMap.a;\n#else\ntranslucencyIntensity*=translucencyIntensityMap.b;\n#endif\n#endif\n#ifdef SS_TRANSLUCENCY\nthickness=maxEps(thickness);vec4 translucencyColor=vTranslucencyColor;\n#ifdef SS_TRANSLUCENCYCOLOR_TEXTURE\ntranslucencyColor*=translucencyColorMap;\n#endif\nvec3 transmittance=transmittanceBRDF_Burley(translucencyColor.rgb,vDiffusionDistance,thickness);transmittance*=translucencyIntensity;outParams.transmittance=transmittance;outParams.translucencyIntensity=translucencyIntensity;\n#endif\n#ifdef SS_REFRACTION\nvec4 environmentRefraction=vec4(0.,0.,0.,0.);\n#ifdef SS_HAS_THICKNESS\nfloat ior=vRefractionInfos.y;\n#else\nfloat ior=vRefractionMicrosurfaceInfos.w;\n#endif\n#ifdef SS_LODINREFRACTIONALPHA\nfloat refractionAlphaG=alphaG;refractionAlphaG=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));float refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,refractionAlphaG,NdotVUnclamped);\n#elif defined(SS_LINEARSPECULARREFRACTION)\nfloat refractionRoughness=alphaG;refractionRoughness=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));float refractionLOD=getLinearLodFromRoughness(vRefractionMicrosurfaceInfos.x,refractionRoughness);\n#else\nfloat refractionAlphaG=alphaG;refractionAlphaG=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));float refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,refractionAlphaG);\n#endif\nfloat refraction_ior=vRefractionInfos.y;\n#ifdef SS_DISPERSION\nfloat realIOR=1.0/refraction_ior;float iorDispersionSpread=0.04*dispersion*(realIOR-1.0);vec3 iors=vec3(1.0/(realIOR-iorDispersionSpread),refraction_ior,1.0/(realIOR+iorDispersionSpread));for (int i=0; i<3; i++) {refraction_ior=iors[i];\n#endif\nvec4 envSample=sampleEnvironmentRefraction(refraction_ior,thickness,refractionLOD,normalW,vPositionW,viewDirectionW,view,vRefractionInfos,refractionMatrix,vRefractionMicrosurfaceInfos,alphaG\n#ifdef SS_REFRACTIONMAP_3D\n,refractionSampler\n#ifndef LODBASEDMICROSFURACE\n,refractionSamplerLow\n,refractionSamplerHigh\n#endif\n#else\n,refractionSampler\n#ifndef LODBASEDMICROSFURACE\n,refractionSamplerLow\n,refractionSamplerHigh\n#endif\n#endif\n#ifdef ANISOTROPIC\n,anisotropicOut\n#endif\n#ifdef REALTIME_FILTERING\n,vRefractionFilteringInfo\n#endif\n#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC\n,refractionPosition\n,refractionSize\n#endif\n);\n#ifdef SS_DISPERSION\nenvironmentRefraction[i]=envSample[i];}\n#else\nenvironmentRefraction=envSample;\n#endif\nenvironmentRefraction.rgb*=vRefractionInfos.x;\n#endif\n#ifdef SS_REFRACTION\nvec3 refractionTransmittance=vec3(refractionIntensity);\n#ifdef SS_THICKNESSANDMASK_TEXTURE\nvec3 volumeAlbedo=computeColorAtDistanceInMedia(vTintColor.rgb,vTintColor.w);refractionTransmittance*=cocaLambert(volumeAlbedo,thickness);\n#elif defined(SS_LINKREFRACTIONTOTRANSPARENCY)\nfloat maxChannel=max(max(surfaceAlbedo.r,surfaceAlbedo.g),surfaceAlbedo.b);vec3 volumeAlbedo=saturate(maxChannel*surfaceAlbedo);environmentRefraction.rgb*=volumeAlbedo;\n#else\nvec3 volumeAlbedo=computeColorAtDistanceInMedia(vTintColor.rgb,vTintColor.w);refractionTransmittance*=cocaLambert(volumeAlbedo,vThicknessParam.y);\n#endif\n#ifdef SS_ALBEDOFORREFRACTIONTINT\nenvironmentRefraction.rgb*=surfaceAlbedo.rgb;\n#endif\noutParams.surfaceAlbedo=surfaceAlbedo*(1.-refractionIntensity);\n#ifdef REFLECTION\noutParams.refractionFactorForIrradiance=(1.-refractionIntensity);\n#endif\n#ifdef UNUSED_MULTIPLEBOUNCES\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);outParams.specularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,refractionIntensity);\n#endif\nrefractionTransmittance*=1.0-outParams.specularEnvironmentReflectance;\n#if DEBUGMODE>0\noutParams.refractionTransmittance=refractionTransmittance;\n#endif\noutParams.finalRefraction=environmentRefraction.rgb*refractionTransmittance*vLightingIntensity.z;\n#if DEBUGMODE>0\noutParams.environmentRefraction=environmentRefraction;\n#endif\n#endif\n#if defined(REFLECTION) && defined(SS_TRANSLUCENCY)\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX) || !defined(USESPHERICALFROMREFLECTIONMAP)\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\n#ifdef INVERTCUBICMAP\nirradianceVector.y*=-1.0;\n#endif\n#else\nvec3 irradianceVector=irradianceVector_;\n#endif\n#if defined(USESPHERICALFROMREFLECTIONMAP)\n#if defined(REALTIME_FILTERING)\nvec3 refractionIrradiance=irradiance(reflectionSampler,-irradianceVector,vReflectionFilteringInfo);\n#else\nvec3 refractionIrradiance=computeEnvironmentIrradiance(-irradianceVector);\n#endif\n#elif defined(USEIRRADIANCEMAP)\n#ifdef REFLECTIONMAP_3D\nvec3 irradianceCoords=irradianceVector;\n#else\nvec2 irradianceCoords=irradianceVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nirradianceCoords/=irradianceVector.z;\n#endif\nirradianceCoords.y=1.0-irradianceCoords.y;\n#endif\nvec4 refractionIrradiance=sampleReflection(irradianceSampler,-irradianceCoords);\n#ifdef RGBDREFLECTION\nrefractionIrradiance.rgb=fromRGBD(refractionIrradiance);\n#endif\n#ifdef GAMMAREFLECTION\nrefractionIrradiance.rgb=toLinearSpace(refractionIrradiance.rgb);\n#endif\n#else\nvec4 refractionIrradiance=vec4(0.);\n#endif\nrefractionIrradiance.rgb*=transmittance;\n#ifdef SS_ALBEDOFORTRANSLUCENCYTINT\nrefractionIrradiance.rgb*=surfaceAlbedo.rgb;\n#endif\noutParams.refractionIrradiance=refractionIrradiance.rgb;\n#endif\nreturn outParams;}\n#endif\n";Je.IncludesShadersStore.clipPlaneFragment="#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";Je.IncludesShadersStore.pbrBlockNormalGeometric="vec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\nvec3 geometricNormalW=normalW;\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\ngeometricNormalW=gl_FrontFacing ? geometricNormalW : -geometricNormalW;\n#endif\n";Je.IncludesShadersStore.bumpFragment="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";Je.IncludesShadersStore.pbrBlockNormalFinal="#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n";Je.IncludesShadersStore.depthPrePass="#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);return;\n#endif\n";Je.IncludesShadersStore.pbrBlockLightmapInit="#ifdef LIGHTMAP\nvec4 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset);\n#ifdef RGBDLIGHTMAP\nlightmapColor.rgb=fromRGBD(lightmapColor);\n#endif\n#ifdef GAMMALIGHTMAP\nlightmapColor.rgb=toLinearSpace(lightmapColor.rgb);\n#endif\nlightmapColor.rgb*=vLightmapInfos.y;\n#endif\n";Je.IncludesShadersStore.pbrBlockGeometryInfo="float NdotVUnclamped=dot(normalW,viewDirectionW);float NdotV=absEps(NdotVUnclamped);float alphaG=convertRoughnessToAverageSlope(roughness);vec2 AARoughnessFactors=getAARoughnessFactors(normalW.xyz);\n#ifdef SPECULARAA\nalphaG+=AARoughnessFactors.y;\n#endif\n#if defined(ENVIRONMENTBRDF)\nvec3 environmentBrdf=getBRDFLookup(NdotV,roughness);\n#endif\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=aoOut.ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(aoOut.ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(-viewDirectionW,normalW,geometricNormalW);\n#endif\n#endif\n#endif\n#endif\n";Je.IncludesShadersStore.pbrBlockReflectance0="float reflectance=max(max(reflectivityOut.surfaceReflectivityColor.r,reflectivityOut.surfaceReflectivityColor.g),reflectivityOut.surfaceReflectivityColor.b);vec3 specularEnvironmentR0=reflectivityOut.surfaceReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec3 specularEnvironmentR90=vec3(metallicReflectanceFactors.a);\n#else \nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0);\n#endif\n#ifdef ALPHAFRESNEL\nfloat reflectance90=fresnelGrazingReflectance(reflectance);specularEnvironmentR90=specularEnvironmentR90*reflectance90;\n#endif\n";Je.IncludesShadersStore.pbrBlockReflectance="#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\nvec3 specularEnvironmentReflectance=getReflectanceFromBRDFLookup(clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,environmentBrdf);\n#ifdef RADIANCEOCCLUSION\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\nvec3 specularEnvironmentReflectance=getReflectanceFromAnalyticalBRDFLookup_Jones(NdotV,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n#ifdef CLEARCOAT\nspecularEnvironmentReflectance*=clearcoatOut.conservationFactor;\n#if defined(CLEARCOAT_TINT)\nspecularEnvironmentReflectance*=clearcoatOut.absorption;\n#endif\n#endif\n";Je.IncludesShadersStore.pbrBlockDirectLighting="vec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef CLEARCOAT\nvec3 clearCoatBase=vec3(0.,0.,0.);\n#endif\n#ifdef SHEEN\nvec3 sheenBase=vec3(0.,0.,0.);\n#endif\npreLightingInfo preInfo;lightingInfo info;float shadow=1.; \nfloat aggShadow=0.;float numLights=0.;\n#if defined(CLEARCOAT) && defined(CLEARCOAT_TINT)\nvec3 absorption=vec3(0.);\n#endif\n";Je.IncludesShadersStore.lightFragment="#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n#else\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,light{X}.vLightDiffuse.rgb,light{X}.vLightGround);\n#elif defined(SS_TRANSLUCENCY)\ninfo.diffuse=computeDiffuseAndTransmittedLighting(preInfo,light{X}.vLightDiffuse.rgb,subSurfaceOut.transmittance);\n#else\ninfo.diffuse=computeDiffuseLighting(preInfo,light{X}.vLightDiffuse.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,light{X}.vLightDiffuse.rgb);\n#else\ninfo.specular=computeSpecularLighting(preInfo,normalW,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.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,light{X}.vLightDiffuse.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,light{X}.vLightDiffuse.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,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightDiffuse.a,glossiness);\n#elif defined(HEMILIGHT{X})\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightGround,glossiness);\n#elif defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightDiffuse.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<SHADOWCSMNUM_CASCADES{X}; i++) \n{\n#ifdef SHADOWCSM_RIGHTHANDED{X}\ndiff{X}=viewFrustumZ{X}[i]+vPositionFromCamera{X}.z;\n#else\ndiff{X}=viewFrustumZ{X}[i]-vPositionFromCamera{X}.z;\n#endif\nif (diff{X}>=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";Je.IncludesShadersStore.pbrBlockFinalLitComponents="aggShadow=aggShadow/numLights;\n#if defined(ENVIRONMENTBRDF)\n#ifdef MS_BRDF_ENERGY_CONSERVATION\nvec3 energyConservationFactor=getEnergyConservationFactor(clearcoatOut.specularEnvironmentR0,environmentBrdf);\n#endif\n#endif\n#ifndef METALLICWORKFLOW\n#ifdef SPECULAR_GLOSSINESS_ENERGY_CONSERVATION\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n#endif\n#endif\n#if defined(SHEEN) && defined(SHEEN_ALBEDOSCALING) && defined(ENVIRONMENTBRDF)\nsurfaceAlbedo.rgb=sheenOut.sheenAlbedoScaling*surfaceAlbedo.rgb;\n#endif\n#ifdef REFLECTION\nvec3 finalIrradiance=reflectionOut.environmentIrradiance;\n#if defined(CLEARCOAT)\nfinalIrradiance*=clearcoatOut.conservationFactor;\n#if defined(CLEARCOAT_TINT)\nfinalIrradiance*=clearcoatOut.absorption;\n#endif\n#endif\n#if defined(SS_REFRACTION)\nfinalIrradiance*=subSurfaceOut.refractionFactorForIrradiance;\n#endif\n#if defined(SS_TRANSLUCENCY)\nfinalIrradiance*=(1.0-subSurfaceOut.translucencyIntensity);finalIrradiance+=subSurfaceOut.refractionIrradiance;\n#endif\nfinalIrradiance*=surfaceAlbedo.rgb;finalIrradiance*=vLightingIntensity.z;finalIrradiance*=aoOut.ambientOcclusionColor;\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;finalSpecular=max(finalSpecular,0.0);vec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)\nfinalSpecularScaled*=energyConservationFactor;\n#endif\n#if defined(SHEEN) && defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING)\nfinalSpecularScaled*=sheenOut.sheenAlbedoScaling;\n#endif\n#endif\n#ifdef REFLECTION\nvec3 finalRadiance=reflectionOut.environmentRadiance.rgb;finalRadiance*=subSurfaceOut.specularEnvironmentReflectance;vec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)\nfinalRadianceScaled*=energyConservationFactor;\n#endif\n#if defined(SHEEN) && defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING)\nfinalRadianceScaled*=sheenOut.sheenAlbedoScaling;\n#endif\n#endif\n#ifdef SHEEN\nvec3 finalSheen=sheenBase*sheenOut.sheenColor;finalSheen=max(finalSheen,0.0);vec3 finalSheenScaled=finalSheen*vLightingIntensity.x*vLightingIntensity.w;\n#if defined(CLEARCOAT) && defined(REFLECTION) && defined(ENVIRONMENTBRDF)\nsheenOut.finalSheenRadianceScaled*=clearcoatOut.conservationFactor;\n#if defined(CLEARCOAT_TINT)\nsheenOut.finalSheenRadianceScaled*=clearcoatOut.absorption;\n#endif\n#endif\n#endif\n#ifdef CLEARCOAT\nvec3 finalClearCoat=clearCoatBase;finalClearCoat=max(finalClearCoat,0.0);vec3 finalClearCoatScaled=finalClearCoat*vLightingIntensity.x*vLightingIntensity.w;\n#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)\nfinalClearCoatScaled*=clearcoatOut.energyConservationFactorClearCoat;\n#endif\n#ifdef SS_REFRACTION\nsubSurfaceOut.finalRefraction*=clearcoatOut.conservationFactor;\n#ifdef CLEARCOAT_TINT\nsubSurfaceOut.finalRefraction*=clearcoatOut.absorption;\n#endif\n#endif\n#endif\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#if defined(CLEARCOAT)\nluminanceOverAlpha+=getLuminance(clearcoatOut.finalClearCoatRadianceScaled);\n#endif\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(CLEARCOAT) && defined(CLEARCOATOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalClearCoatScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA) || defined(CLEARCOATOVERALPHA)\nalpha=saturate(alpha+luminanceOverAlpha*luminanceOverAlpha);\n#endif\n#endif\n";Je.IncludesShadersStore.pbrBlockFinalUnlitComponents="vec3 finalDiffuse=diffuseBase;finalDiffuse*=surfaceAlbedo.rgb;finalDiffuse=max(finalDiffuse,0.0);finalDiffuse*=vLightingIntensity.x;vec3 finalAmbient=vAmbientColor;finalAmbient*=surfaceAlbedo.rgb;vec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\n#ifdef GAMMAEMISSIVE\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\n#else\nfinalEmissive*=emissiveColorTex.rgb;\n#endif\nfinalEmissive*= vEmissiveInfos.y;\n#endif\nfinalEmissive*=vLightingIntensity.y;\n#ifdef AMBIENT\nvec3 ambientOcclusionForDirectDiffuse=mix(vec3(1.),aoOut.ambientOcclusionColor,vAmbientInfos.w);\n#else\nvec3 ambientOcclusionForDirectDiffuse=aoOut.ambientOcclusionColor;\n#endif\nfinalAmbient*=aoOut.ambientOcclusionColor;finalDiffuse*=ambientOcclusionForDirectDiffuse;\n";Je.IncludesShadersStore.pbrBlockFinalColorComposition="vec4 finalColor=vec4(\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance +\n#endif\n#ifdef SPECULARTERM\nfinalSpecularScaled +\n#endif\n#ifdef SHEEN\nfinalSheenScaled +\n#endif\n#ifdef CLEARCOAT\nfinalClearCoatScaled +\n#endif\n#ifdef REFLECTION\nfinalRadianceScaled +\n#if defined(SHEEN) && defined(ENVIRONMENTBRDF)\nsheenOut.finalSheenRadianceScaled +\n#endif\n#ifdef CLEARCOAT\nclearcoatOut.finalClearCoatRadianceScaled +\n#endif\n#endif\n#ifdef SS_REFRACTION\nsubSurfaceOut.finalRefraction +\n#endif\n#endif\nfinalAmbient +\nfinalDiffuse,\nalpha);\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor.rgb;\n#else\nfinalColor.rgb+=lightmapColor.rgb;\n#endif\n#endif\n#endif\nfinalColor.rgb+=finalEmissive;\n#define CUSTOM_FRAGMENT_BEFORE_FOG\nfinalColor=max(finalColor,0.0);\n";Je.IncludesShadersStore.logDepthFragment="#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif\n";Je.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";Je.IncludesShadersStore.pbrBlockImageProcessing="#if defined(IMAGEPROCESSINGPOSTPROCESS) || defined(SS_SCATTERING)\n#if !defined(SKIPFINALCOLORCLAMP)\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#endif\n#else\nfinalColor=applyImageProcessing(finalColor);\n#endif\nfinalColor.a*=visibility;\n#ifdef PREMULTIPLYALPHA\nfinalColor.rgb*=finalColor.a;\n#endif\n";Je.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 || fragDepth<furthestDepth) {\n#else\nif (fragDepth<nearestDepth || fragDepth>furthestDepth) {\n#endif\nreturn;}\n#ifdef USE_REVERSE_DEPTHBUFFER\nif (fragDepth<nearestDepth && fragDepth>furthestDepth) {\n#else\nif (fragDepth>nearestDepth && fragDepth<furthestDepth) {\n#endif\ndepth.rg=vec2(-fragDepth,fragDepth);return;}\n#endif\n";Je.IncludesShadersStore.pbrDebug="#if DEBUGMODE>0\nif (vClipSpacePosition.x/vClipSpacePosition.w>=vDebugMode.x) {\n#if DEBUGMODE==1\ngl_FragColor.rgb=vPositionW.rgb;\n#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==2 && defined(NORMAL)\ngl_FragColor.rgb=vNormalW.rgb;\n#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==3 && defined(BUMP) || DEBUGMODE==3 && defined(PARALLAX) || DEBUGMODE==3 && defined(ANISOTROPIC)\ngl_FragColor.rgb=TBN[0];\n#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==4 && defined(BUMP) || DEBUGMODE==4 && defined(PARALLAX) || DEBUGMODE==4 && defined(ANISOTROPIC)\ngl_FragColor.rgb=TBN[1];\n#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==5\ngl_FragColor.rgb=normalW;\n#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==6 && defined(MAINUV1)\ngl_FragColor.rgb=vec3(vMainUV1,0.0);\n#elif DEBUGMODE==7 && defined(MAINUV2)\ngl_FragColor.rgb=vec3(vMainUV2,0.0);\n#elif DEBUGMODE==8 && defined(CLEARCOAT) && defined(CLEARCOAT_BUMP)\ngl_FragColor.rgb=clearcoatOut.TBNClearCoat[0];\n#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==9 && defined(CLEARCOAT) && defined(CLEARCOAT_BUMP)\ngl_FragColor.rgb=clearcoatOut.TBNClearCoat[1];\n#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==10 && defined(CLEARCOAT)\ngl_FragColor.rgb=clearcoatOut.clearCoatNormalW;\n#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==11 && defined(ANISOTROPIC)\ngl_FragColor.rgb=anisotropicOut.anisotropicNormal;\n#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==12 && defined(ANISOTROPIC)\ngl_FragColor.rgb=anisotropicOut.anisotropicTangent;\n#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==13 && defined(ANISOTROPIC)\ngl_FragColor.rgb=anisotropicOut.anisotropicBitangent;\n#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==20 && defined(ALBEDO)\ngl_FragColor.rgb=albedoTexture.rgb;\n#ifndef GAMMAALBEDO\n#define DEBUGMODE_GAMMA\n#endif\n#elif DEBUGMODE==21 && defined(AMBIENT)\ngl_FragColor.rgb=aoOut.ambientOcclusionColorMap.rgb;\n#elif DEBUGMODE==22 && defined(OPACITY)\ngl_FragColor.rgb=opacityMap.rgb;\n#elif DEBUGMODE==23 && defined(EMISSIVE)\ngl_FragColor.rgb=emissiveColorTex.rgb;\n#ifndef GAMMAEMISSIVE\n#define DEBUGMODE_GAMMA\n#endif\n#elif DEBUGMODE==24 && defined(LIGHTMAP)\ngl_FragColor.rgb=lightmapColor.rgb;\n#ifndef GAMMALIGHTMAP\n#define DEBUGMODE_GAMMA\n#endif\n#elif DEBUGMODE==25 && defined(REFLECTIVITY) && defined(METALLICWORKFLOW)\ngl_FragColor.rgb=reflectivityOut.surfaceMetallicColorMap.rgb;\n#elif DEBUGMODE==26 && defined(REFLECTIVITY) && !defined(METALLICWORKFLOW)\ngl_FragColor.rgb=reflectivityOut.surfaceReflectivityColorMap.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==27 && defined(CLEARCOAT) && defined(CLEARCOAT_TEXTURE)\ngl_FragColor.rgb=vec3(clearcoatOut.clearCoatMapData.rg,0.0);\n#elif DEBUGMODE==28 && defined(CLEARCOAT) && defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE)\ngl_FragColor.rgb=clearcoatOut.clearCoatTintMapData.rgb;\n#elif DEBUGMODE==29 && defined(SHEEN) && defined(SHEEN_TEXTURE)\ngl_FragColor.rgb=sheenOut.sheenMapData.rgb;\n#elif DEBUGMODE==30 && defined(ANISOTROPIC) && defined(ANISOTROPIC_TEXTURE)\ngl_FragColor.rgb=anisotropicOut.anisotropyMapData.rgb;\n#elif DEBUGMODE==31 && defined(SUBSURFACE) && defined(SS_THICKNESSANDMASK_TEXTURE)\ngl_FragColor.rgb=subSurfaceOut.thicknessMap.rgb;\n#elif DEBUGMODE==32 && defined(BUMP)\ngl_FragColor.rgb=texture2D(bumpSampler,vBumpUV).rgb;\n#elif DEBUGMODE==40 && defined(SS_REFRACTION)\ngl_FragColor.rgb=subSurfaceOut.environmentRefraction.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==41 && defined(REFLECTION)\ngl_FragColor.rgb=reflectionOut.environmentRadiance.rgb;\n#ifndef GAMMAREFLECTION\n#define DEBUGMODE_GAMMA\n#endif\n#elif DEBUGMODE==42 && defined(CLEARCOAT) && defined(REFLECTION)\ngl_FragColor.rgb=clearcoatOut.environmentClearCoatRadiance.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==50\ngl_FragColor.rgb=diffuseBase.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==51 && defined(SPECULARTERM)\ngl_FragColor.rgb=specularBase.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==52 && defined(CLEARCOAT)\ngl_FragColor.rgb=clearCoatBase.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==53 && defined(SHEEN)\ngl_FragColor.rgb=sheenBase.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==54 && defined(REFLECTION)\ngl_FragColor.rgb=reflectionOut.environmentIrradiance.rgb;\n#ifndef GAMMAREFLECTION\n#define DEBUGMODE_GAMMA\n#endif\n#elif DEBUGMODE==60\ngl_FragColor.rgb=surfaceAlbedo.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==61\ngl_FragColor.rgb=clearcoatOut.specularEnvironmentR0;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==62 && defined(METALLICWORKFLOW)\ngl_FragColor.rgb=vec3(reflectivityOut.metallicRoughness.r);\n#elif DEBUGMODE==71 && defined(METALLICWORKFLOW)\ngl_FragColor.rgb=reflectivityOut.metallicF0;\n#elif DEBUGMODE==63\ngl_FragColor.rgb=vec3(roughness);\n#elif DEBUGMODE==64\ngl_FragColor.rgb=vec3(alphaG);\n#elif DEBUGMODE==65\ngl_FragColor.rgb=vec3(NdotV);\n#elif DEBUGMODE==66 && defined(CLEARCOAT) && defined(CLEARCOAT_TINT)\ngl_FragColor.rgb=clearcoatOut.clearCoatColor.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==67 && defined(CLEARCOAT)\ngl_FragColor.rgb=vec3(clearcoatOut.clearCoatRoughness);\n#elif DEBUGMODE==68 && defined(CLEARCOAT)\ngl_FragColor.rgb=vec3(clearcoatOut.clearCoatNdotV);\n#elif DEBUGMODE==69 && defined(SUBSURFACE) && defined(SS_TRANSLUCENCY)\ngl_FragColor.rgb=subSurfaceOut.transmittance;\n#elif DEBUGMODE==70 && defined(SUBSURFACE) && defined(SS_REFRACTION)\ngl_FragColor.rgb=subSurfaceOut.refractionTransmittance;\n#elif DEBUGMODE==72\ngl_FragColor.rgb=vec3(microSurface);\n#elif DEBUGMODE==73\ngl_FragColor.rgb=vAlbedoColor.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==74 && !defined(METALLICWORKFLOW)\ngl_FragColor.rgb=vReflectivityColor.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==75\ngl_FragColor.rgb=vEmissiveColor.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==80 && defined(RADIANCEOCCLUSION)\ngl_FragColor.rgb=vec3(seo);\n#elif DEBUGMODE==81 && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D)\ngl_FragColor.rgb=vec3(eho);\n#elif DEBUGMODE==82 && defined(MS_BRDF_ENERGY_CONSERVATION)\ngl_FragColor.rgb=vec3(energyConservationFactor);\n#elif DEBUGMODE==83 && defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\ngl_FragColor.rgb=specularEnvironmentReflectance;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==84 && defined(CLEARCOAT) && defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\ngl_FragColor.rgb=clearcoatOut.clearCoatEnvironmentReflectance;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==85 && defined(SHEEN) && defined(REFLECTION)\ngl_FragColor.rgb=sheenOut.sheenEnvironmentReflectance;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==86 && defined(ALPHABLEND)\ngl_FragColor.rgb=vec3(luminanceOverAlpha);\n#elif DEBUGMODE==87\ngl_FragColor.rgb=vec3(alpha);\n#elif DEBUGMODE==88 && defined(ALBEDO)\ngl_FragColor.rgb=vec3(albedoTexture.a);\n#elif DEBUGMODE==89\ngl_FragColor.rgb=aoOut.ambientOcclusionColor.rgb;\n#else\nfloat stripeWidth=30.;float stripePos=floor(gl_FragCoord.x/stripeWidth);float whichColor=mod(stripePos,2.);vec3 color1=vec3(.6,.2,.2);vec3 color2=vec3(.3,.1,.1);gl_FragColor.rgb=mix(color1,color2,whichColor);\n#endif\ngl_FragColor.rgb*=vDebugMode.y;\n#ifdef DEBUGMODE_NORMALIZE\ngl_FragColor.rgb=normalize(gl_FragColor.rgb)*0.5+0.5;\n#endif\n#ifdef DEBUGMODE_GAMMA\ngl_FragColor.rgb=toGammaSpace(gl_FragColor.rgb);\n#endif\ngl_FragColor.a=1.0;\n#ifdef PREPASS\ngl_FragData[0]=toLinearSpace(gl_FragColor); \ngl_FragData[1]=vec4(0.,0.,0.,0.); \n#endif\n#ifdef DEBUGMODE_FORCERETURN\nreturn;\n#endif\n}\n#endif\n";const Hu="pbrPixelShader",Wu="#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include<prePassDeclaration>[SCENE_MRT_COUNT]\nprecision highp float;\n#include<oitDeclaration>\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE\n#endif\n#include<__decl__pbrFragment>\n#include<pbrFragmentExtraDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<pbrFragmentSamplersDeclaration>\n#include<imageProcessingDeclaration>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#include<helperFunctions>\n#include<subSurfaceScatteringFunctions>\n#include<importanceSampling>\n#include<pbrHelperFunctions>\n#include<imageProcessingFunctions>\n#include<shadowsFragmentFunctions>\n#include<harmonicsFunctions>\n#include<pbrDirectLightingSetupFunctions>\n#include<pbrDirectLightingFalloffFunctions>\n#include<pbrBRDFFunctions>\n#include<hdrFilteringFunctions>\n#include<pbrDirectLightingFunctions>\n#include<pbrIBLFunctions>\n#include<bumpFragmentMainFunctions>\n#include<bumpFragmentFunctions>\n#ifdef REFLECTION\n#include<reflectionFunction>\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\n#include<pbrBlockAlbedoOpacity>\n#include<pbrBlockReflectivity>\n#include<pbrBlockAmbientOcclusion>\n#include<pbrBlockAlphaFresnel>\n#include<pbrBlockAnisotropic>\n#include<pbrBlockReflection>\n#include<pbrBlockSheen>\n#include<pbrBlockClearcoat>\n#include<pbrBlockIridescence>\n#include<pbrBlockSubSurface>\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\n#include<pbrBlockNormalGeometric>\n#include<bumpFragment>\n#include<pbrBlockNormalFinal>\nalbedoOpacityOutParams albedoOpacityOut;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#endif\n#ifdef DECAL\nvec4 decalColor=texture2D(decalSampler,vDecalUV+uvOffset);\n#endif\nalbedoOpacityOut=albedoOpacityBlock(\nvAlbedoColor\n#ifdef ALBEDO\n,albedoTexture\n,vAlbedoInfos\n#endif\n#ifdef OPACITY\n,opacityMap\n,vOpacityInfos\n#endif\n#ifdef DETAIL\n,detailColor\n,vDetailInfos\n#endif\n#ifdef DECAL\n,decalColor\n,vDecalInfos\n#endif\n);vec3 surfaceAlbedo=albedoOpacityOut.surfaceAlbedo;float alpha=albedoOpacityOut.alpha;\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\n#include<depthPrePass>\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\nambientOcclusionOutParams aoOut;\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb;\n#endif\naoOut=ambientOcclusionBlock(\n#ifdef AMBIENT\nambientOcclusionColorMap,\nvAmbientInfos\n#endif \n);\n#include<pbrBlockLightmapInit>\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\nvec3 baseColor=surfaceAlbedo;reflectivityOutParams reflectivityOut;\n#if defined(REFLECTIVITY)\nvec4 surfaceMetallicOrReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);vec4 baseReflectivity=surfaceMetallicOrReflectivityColorMap;\n#ifndef METALLICWORKFLOW\n#ifdef REFLECTIVITY_GAMMA\nsurfaceMetallicOrReflectivityColorMap=toLinearSpace(surfaceMetallicOrReflectivityColorMap);\n#endif\nsurfaceMetallicOrReflectivityColorMap.rgb*=vReflectivityInfos.y;\n#endif\n#endif\n#if defined(MICROSURFACEMAP)\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\n#endif\n#ifdef METALLICWORKFLOW\nvec4 metallicReflectanceFactors=vMetallicReflectanceFactors;\n#ifdef REFLECTANCE\nvec4 reflectanceFactorsMap=texture2D(reflectanceSampler,vReflectanceUV+uvOffset);\n#ifdef REFLECTANCE_GAMMA\nreflectanceFactorsMap=toLinearSpace(reflectanceFactorsMap);\n#endif\nmetallicReflectanceFactors.rgb*=reflectanceFactorsMap.rgb;\n#endif\n#ifdef METALLIC_REFLECTANCE\nvec4 metallicReflectanceFactorsMap=texture2D(metallicReflectanceSampler,vMetallicReflectanceUV+uvOffset);\n#ifdef METALLIC_REFLECTANCE_GAMMA\nmetallicReflectanceFactorsMap=toLinearSpace(metallicReflectanceFactorsMap);\n#endif\n#ifndef METALLIC_REFLECTANCE_USE_ALPHA_ONLY\nmetallicReflectanceFactors.rgb*=metallicReflectanceFactorsMap.rgb;\n#endif\nmetallicReflectanceFactors*=metallicReflectanceFactorsMap.a;\n#endif\n#endif\nreflectivityOut=reflectivityBlock(\nvReflectivityColor\n#ifdef METALLICWORKFLOW\n,surfaceAlbedo\n,metallicReflectanceFactors\n#endif\n#ifdef REFLECTIVITY\n,vReflectivityInfos\n,surfaceMetallicOrReflectivityColorMap\n#endif\n#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)\n,aoOut.ambientOcclusionColor\n#endif\n#ifdef MICROSURFACEMAP\n,microSurfaceTexel\n#endif\n#ifdef DETAIL\n,detailColor\n,vDetailInfos\n#endif\n);float microSurface=reflectivityOut.microSurface;float roughness=reflectivityOut.roughness;\n#ifdef METALLICWORKFLOW\nsurfaceAlbedo=reflectivityOut.surfaceAlbedo;\n#endif\n#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)\naoOut.ambientOcclusionColor=reflectivityOut.ambientOcclusionColor;\n#endif\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\nalphaFresnelOutParams alphaFresnelOut;alphaFresnelOut=alphaFresnelBlock(\nnormalW,\nviewDirectionW,\nalpha,\nmicroSurface\n);alpha=alphaFresnelOut.alpha;\n#endif\n#endif\n#include<pbrBlockGeometryInfo>\n#ifdef ANISOTROPIC\nanisotropicOutParams anisotropicOut;\n#ifdef ANISOTROPIC_TEXTURE\nvec3 anisotropyMapData=texture2D(anisotropySampler,vAnisotropyUV+uvOffset).rgb*vAnisotropyInfos.y;\n#endif\nanisotropicOut=anisotropicBlock(\nvAnisotropy,\nroughness,\n#ifdef ANISOTROPIC_TEXTURE\nanisotropyMapData,\n#endif\nTBN,\nnormalW,\nviewDirectionW \n);\n#endif\n#ifdef REFLECTION\nreflectionOutParams reflectionOut;\n#ifndef USE_CUSTOM_REFLECTION\nreflectionOut=reflectionBlock(\nvPositionW\n,normalW\n,alphaG\n,vReflectionMicrosurfaceInfos\n,vReflectionInfos\n,vReflectionColor\n#ifdef ANISOTROPIC\n,anisotropicOut\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\n,NdotVUnclamped\n#endif\n#ifdef LINEARSPECULARREFLECTION\n,roughness\n#endif\n,reflectionSampler\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\n,vEnvironmentIrradiance\n#endif\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)\n,reflectionMatrix\n#endif\n#endif\n#ifdef USEIRRADIANCEMAP\n,irradianceSampler\n#endif\n#ifndef LODBASEDMICROSFURACE\n,reflectionSamplerLow\n,reflectionSamplerHigh\n#endif\n#ifdef REALTIME_FILTERING\n,vReflectionFilteringInfo\n#endif\n);\n#else\n#define CUSTOM_REFLECTION\n#endif\n#endif\n#include<pbrBlockReflectance0>\n#ifdef SHEEN\nsheenOutParams sheenOut;\n#ifdef SHEEN_TEXTURE\nvec4 sheenMapData=texture2D(sheenSampler,vSheenUV+uvOffset);\n#endif\n#if defined(SHEEN_ROUGHNESS) && defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE)\nvec4 sheenMapRoughnessData=texture2D(sheenRoughnessSampler,vSheenRoughnessUV+uvOffset)*vSheenInfos.w;\n#endif\nsheenOut=sheenBlock(\nvSheenColor\n#ifdef SHEEN_ROUGHNESS\n,vSheenRoughness\n#if defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE)\n,sheenMapRoughnessData\n#endif\n#endif\n,roughness\n#ifdef SHEEN_TEXTURE\n,sheenMapData\n,vSheenInfos.y\n#endif\n,reflectance\n#ifdef SHEEN_LINKWITHALBEDO\n,baseColor\n,surfaceAlbedo\n#endif\n#ifdef ENVIRONMENTBRDF\n,NdotV\n,environmentBrdf\n#endif\n#if defined(REFLECTION) && defined(ENVIRONMENTBRDF)\n,AARoughnessFactors\n,vReflectionMicrosurfaceInfos\n,vReflectionInfos\n,vReflectionColor\n,vLightingIntensity\n,reflectionSampler\n,reflectionOut.reflectionCoords\n,NdotVUnclamped\n#ifndef LODBASEDMICROSFURACE\n,reflectionSamplerLow\n,reflectionSamplerHigh\n#endif\n#ifdef REALTIME_FILTERING\n,vReflectionFilteringInfo\n#endif\n#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION)\n,seo\n#endif\n#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D)\n,eho\n#endif\n#endif\n);\n#ifdef SHEEN_LINKWITHALBEDO\nsurfaceAlbedo=sheenOut.surfaceAlbedo;\n#endif\n#endif\n#ifdef CLEARCOAT\n#ifdef CLEARCOAT_TEXTURE\nvec2 clearCoatMapData=texture2D(clearCoatSampler,vClearCoatUV+uvOffset).rg*vClearCoatInfos.y;\n#endif\n#endif\n#ifdef IRIDESCENCE\niridescenceOutParams iridescenceOut;\n#ifdef IRIDESCENCE_TEXTURE\nvec2 iridescenceMapData=texture2D(iridescenceSampler,vIridescenceUV+uvOffset).rg*vIridescenceInfos.y;\n#endif\n#ifdef IRIDESCENCE_THICKNESS_TEXTURE\nvec2 iridescenceThicknessMapData=texture2D(iridescenceThicknessSampler,vIridescenceThicknessUV+uvOffset).rg*vIridescenceInfos.w;\n#endif\niridescenceOut=iridescenceBlock(\nvIridescenceParams\n,NdotV\n,specularEnvironmentR0\n#ifdef IRIDESCENCE_TEXTURE\n,iridescenceMapData\n#endif\n#ifdef IRIDESCENCE_THICKNESS_TEXTURE\n,iridescenceThicknessMapData\n#endif\n#ifdef CLEARCOAT\n,NdotVUnclamped\n#ifdef CLEARCOAT_TEXTURE\n,clearCoatMapData\n#endif\n#endif\n);float iridescenceIntensity=iridescenceOut.iridescenceIntensity;specularEnvironmentR0=iridescenceOut.specularEnvironmentR0;\n#endif\nclearcoatOutParams clearcoatOut;\n#ifdef CLEARCOAT\n#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE)\nvec4 clearCoatMapRoughnessData=texture2D(clearCoatRoughnessSampler,vClearCoatRoughnessUV+uvOffset)*vClearCoatInfos.w;\n#endif\n#if defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE)\nvec4 clearCoatTintMapData=texture2D(clearCoatTintSampler,vClearCoatTintUV+uvOffset);\n#endif\n#ifdef CLEARCOAT_BUMP\nvec4 clearCoatBumpMapData=texture2D(clearCoatBumpSampler,vClearCoatBumpUV+uvOffset);\n#endif\nclearcoatOut=clearcoatBlock(\nvPositionW\n,geometricNormalW\n,viewDirectionW\n,vClearCoatParams\n#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE)\n,clearCoatMapRoughnessData\n#endif\n,specularEnvironmentR0\n#ifdef CLEARCOAT_TEXTURE\n,clearCoatMapData\n#endif\n#ifdef CLEARCOAT_TINT\n,vClearCoatTintParams\n,clearCoatColorAtDistance\n,vClearCoatRefractionParams\n#ifdef CLEARCOAT_TINT_TEXTURE\n,clearCoatTintMapData\n#endif\n#endif\n#ifdef CLEARCOAT_BUMP\n,vClearCoatBumpInfos\n,clearCoatBumpMapData\n,vClearCoatBumpUV\n#if defined(TANGENT) && defined(NORMAL)\n,vTBN\n#else\n,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,vReflectionMicrosurfaceInfos\n,vReflectionInfos\n,vReflectionColor\n,vLightingIntensity\n,reflectionSampler\n#ifndef LODBASEDMICROSFURACE\n,reflectionSamplerLow\n,reflectionSamplerHigh\n#endif\n#ifdef REALTIME_FILTERING\n,vReflectionFilteringInfo\n#endif\n#endif\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n#ifdef RADIANCEOCCLUSION\n,ambientMonochrome\n#endif\n#endif\n#if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING)\n,(gl_FrontFacing ? 1. : -1.)\n#endif\n);\n#else\nclearcoatOut.specularEnvironmentR0=specularEnvironmentR0;\n#endif\n#include<pbrBlockReflectance>\nsubSurfaceOutParams subSurfaceOut;\n#ifdef SUBSURFACE\n#ifdef SS_THICKNESSANDMASK_TEXTURE\nvec4 thicknessMap=texture2D(thicknessSampler,vThicknessUV+uvOffset);\n#endif\n#ifdef SS_REFRACTIONINTENSITY_TEXTURE\nvec4 refractionIntensityMap=texture2D(refractionIntensitySampler,vRefractionIntensityUV+uvOffset);\n#endif\n#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE\nvec4 translucencyIntensityMap=texture2D(translucencyIntensitySampler,vTranslucencyIntensityUV+uvOffset);\n#endif\n#ifdef SS_TRANSLUCENCYCOLOR_TEXTURE\nvec4 translucencyColorMap=texture2D(translucencyColorSampler,vTranslucencyColorUV+uvOffset);\n#endif\nsubSurfaceOut=subSurfaceBlock(\nvSubSurfaceIntensity\n,vThicknessParam\n,vTintColor\n,normalW\n,specularEnvironmentReflectance\n#ifdef SS_THICKNESSANDMASK_TEXTURE\n,thicknessMap\n#endif\n#ifdef SS_REFRACTIONINTENSITY_TEXTURE\n,refractionIntensityMap\n#endif\n#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE\n,translucencyIntensityMap\n#endif\n#ifdef REFLECTION\n#ifdef SS_TRANSLUCENCY\n,reflectionMatrix\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)\n,reflectionOut.irradianceVector\n#endif\n#if defined(REALTIME_FILTERING)\n,reflectionSampler\n,vReflectionFilteringInfo\n#endif\n#endif\n#ifdef USEIRRADIANCEMAP\n,irradianceSampler\n#endif\n#endif\n#endif\n#if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY)\n,surfaceAlbedo\n#endif\n#ifdef SS_REFRACTION\n,vPositionW\n,viewDirectionW\n,view\n,vRefractionInfos\n,refractionMatrix\n,vRefractionMicrosurfaceInfos\n,vLightingIntensity\n#ifdef SS_LINKREFRACTIONTOTRANSPARENCY\n,alpha\n#endif\n#ifdef SS_LODINREFRACTIONALPHA\n,NdotVUnclamped\n#endif\n#ifdef SS_LINEARSPECULARREFRACTION\n,roughness\n#endif\n,alphaG\n,refractionSampler\n#ifndef LODBASEDMICROSFURACE\n,refractionSamplerLow\n,refractionSamplerHigh\n#endif\n#ifdef ANISOTROPIC\n,anisotropicOut\n#endif\n#ifdef REALTIME_FILTERING\n,vRefractionFilteringInfo\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,vDiffusionDistance\n,vTranslucencyColor\n#ifdef SS_TRANSLUCENCYCOLOR_TEXTURE\n,translucencyColorMap\n#endif\n#endif\n);\n#ifdef SS_REFRACTION\nsurfaceAlbedo=subSurfaceOut.surfaceAlbedo;\n#ifdef SS_LINKREFRACTIONTOTRANSPARENCY\nalpha=subSurfaceOut.alpha;\n#endif\n#endif\n#else\nsubSurfaceOut.specularEnvironmentReflectance=specularEnvironmentReflectance;\n#endif\n#include<pbrBlockDirectLighting>\n#include<lightFragment>[0..maxSimultaneousLights]\n#include<pbrBlockFinalLitComponents>\n#endif \n#include<pbrBlockFinalUnlitComponents>\n#define CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION\n#include<pbrBlockFinalColorComposition>\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#include<pbrBlockImageProcessing>\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\n#ifdef PREPASS\nfloat writeGeometryInfo=finalColor.a>0.4 ? 1.0 : 0.0;\n#ifdef PREPASS_POSITION\ngl_FragData[PREPASS_POSITION_INDEX]=vec4(vPositionW,writeGeometryInfo);\n#endif\n#ifdef 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#endif\n#ifdef PREPASS_ALBEDO_SQRT\nvec3 sqAlbedo=sqrt(surfaceAlbedo); \n#endif\n#ifdef PREPASS_IRRADIANCE\nvec3 irradiance=finalDiffuse;\n#ifndef UNLIT\n#ifdef REFLECTION\nirradiance+=finalIrradiance;\n#endif\n#endif\n#ifdef SS_SCATTERING\ngl_FragData[0]=vec4(finalColor.rgb-irradiance,finalColor.a); \nirradiance/=sqAlbedo;\n#else\ngl_FragData[0]=finalColor; \nfloat scatteringDiffusionProfile=255.;\n#endif\ngl_FragData[PREPASS_IRRADIANCE_INDEX]=vec4(clamp(irradiance,vec3(0.),vec3(1.)),writeGeometryInfo*scatteringDiffusionProfile/255.); \n#else\ngl_FragData[0]=vec4(finalColor.rgb,finalColor.a);\n#endif\n#ifdef PREPASS_DEPTH\ngl_FragData[PREPASS_DEPTH_INDEX]=vec4(vViewPos.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_ALBEDO_SQRT\ngl_FragData[PREPASS_ALBEDO_SQRT_INDEX]=vec4(sqAlbedo,writeGeometryInfo); \n#endif\n#ifdef PREPASS_REFLECTIVITY\n#ifndef UNLIT\ngl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(specularEnvironmentR0,microSurface)*writeGeometryInfo;\n#else\ngl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4( 0.0,0.0,0.0,1.0 )*writeGeometryInfo;\n#endif\n#endif\n#endif\n#if !defined(PREPASS) || defined(WEBGL2)\ngl_FragColor=finalColor;\n#endif\n#include<oitFragment>\n#if ORDER_INDEPENDENT_TRANSPARENCY\nif (fragDepth==nearestDepth) {frontColor.rgb+=finalColor.rgb*finalColor.a*alphaMultiplier;frontColor.a=1.0-alphaMultiplier*(1.0-finalColor.a);} else {backColor+=finalColor;}\n#endif\n#include<pbrDebug>\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";Je.ShadersStore[Hu]=Wu;const zu={name:Hu,shader:Wu};var Yu=Object.freeze({__proto__:null,pbrPixelShader:zu});export{Od as HTML3DElement,Rd as Viewer,yd as createViewerForCanvas};
2
+ //# sourceMappingURL=babylon-viewer.esm.min.js.map